2016-01-04 54 views
8
#include <iostream> 
#include <string> 

constexpr std::string appendStringC(std::string s) 
{ 
    return s + " Constexpr func"; 
} 

std::string appendString(std::string s) 
{ 
    return s + " Regular func"; 
} 

int main() 
{ 
    std::string s1 = "String 1"; 
    std::string s2 = "String 2"; 
    std::cout << std::endl 
       << appendStringC(s1) << std::endl 
       << appendString(s2) << std::endl; 
    return 0; 
} 

我試圖執行使用constexpr編譯時間字符串前綴/後綴串聯操作。然而,這個例子產生以下錯誤:編譯時字符串連接constexpr

const_string_generation.cpp: In function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’: 
const_string_generation.cpp:4:23: error: invalid type for parameter 1 of constexpr function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’ 
constexpr std::string appendStringC(std::string s) 
        ^
In file included from /usr/include/c++/5.3.0/string:52:0, 
       from /usr/include/c++/5.3.0/bits/locale_classes.h:40, 
       from /usr/include/c++/5.3.0/bits/ios_base.h:41, 
       from /usr/include/c++/5.3.0/ios:42, 
       from /usr/include/c++/5.3.0/ostream:38, 
       from /usr/include/c++/5.3.0/iostream:39, 
       from const_string_generation.cpp:1: 
/usr/include/c++/5.3.0/bits/basic_string.h:71:11: note: ‘std::__cxx11::basic_string<char>’ is not literal because: 
    class basic_string 
     ^
/usr/include/c++/5.3.0/bits/basic_string.h:71:11: note: ‘std::__cxx11::basic_string<char>’ has a non-trivial destructor 
const_string_generation.cpp:4:23: error: invalid return type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ of constexpr function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’ 
constexpr std::string appendStringC(std::string s) 

因爲std :: string不是一個文字。我正在尋找一個簡單的方法來做到這一點,我不關心這個例子的後向兼容性。 Ideone:Link


+4

你不能,因爲'std :: string'通常在內部使用動態分配(不是很「constexpr」友好)。但是,您可以通過將它們依次放置來連接兩個或多個字符串*文字*。 –

+0

@ Cheersandhth.-Alf是的,但我有很多很長的字符串,我需要在前面或有時在字符串後面連接。有點像轉義碼,所以手動放置和編輯它們中的每一個都可能很快變得笨拙。 –

+0

你可以使用字符序列,像http://stackoverflow.com/a/22067775/2684539 – Jarod42

回答

5

std:string::operator+()不是constexpr,實際上它是在依賴於堆內存非常動態的方式通常執行。你可以像這樣附加靜態字符串常量:

"append this string " " to this string"