使用constexpr编译时间字符串连接

时间:2016-01-04 11:35:20

标签: c++ string

#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执行编译时字符串前缀/后缀连接操作。但是,此示例产生以下错误:

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

1 个答案:

答案 0 :(得分:5)

std:string::operator+()不是constexpr,实际上它通常以非常动态的方式实现,依赖于堆内存。您可以添加如下静态字符串常量:

"append this string " " to this string"