使用constexpr编译时间字符串连接 [英] compile time string concatenation using constexpr

查看:301
本文介绍了使用constexpr编译时间字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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执行编译时字符串prefix / postfix连接操作。然而,这个例子产生以下错误:


I'm trying to perform compile time string prefix/postfix concatenation operation using constexpr. However this example is producing following errors:

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:链接

since std::string isn't a literal. I'm looking for an easy way to do this and I don't care about backward compatiblity for this very example. Ideone : Link

推荐答案

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

std:string::operator+() isn't a constexpr, in fact it's usually implemented in a very dynamic manner that relies on heap memory. You can append static string constants like this:

"append this string " " to this string"

这篇关于使用constexpr编译时间字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆