使用 constexpr 编译时间字符串串联

compile time string concatenation using constexpr

本文关键字:字符串 时间 constexpr 编译 使用      更新时间:2023-10-16
#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 : 链接


std:string::operator+()不是一个constexpr,事实上它通常以依赖于堆内存的非常动态的方式实现。 您可以像这样附加静态字符串常量:

"append this string " " to this string"