【问题标题】:compile time string concatenation using constexpr使用 constexpr 编译时字符串连接
【发布时间】:2016-01-04 11:35:19
【问题描述】:
#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 不是文字。我正在寻找一种简单的方法来做到这一点,我并不关心这个例子的向后兼容性。爱迪生:Link


【问题讨论】:

  • 你不能,因为std::string通常在内部使用动态分配(不是很友好constexpr)。但是,您可以连接两个或多个字符串 literals,只需将它们按顺序放置即可。
  • @Cheersandhth.-Alf 是的,但我有很多长字符串需要在字符串前面或有时后面连接。有点像转义码,因此手动放置和编辑它们中的每一个可能很快就会变得笨拙。
  • 你可以使用字符序列,比如stackoverflow.com/a/22067775/2684539
  • @Jarod42 太麻烦了,如果没有用,我只会抛出一个 hacky 宏方法。

标签: c++ string


【解决方案1】:

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

"append this string " " to this string"

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多