如何在编译期间将const字符串初始化为两个字符串的连接
How to initialize a const string as the concatenation of two strings during compilation time?
下面的代码在编译时初始化了两个const字符串:
class Test
{
public:
static constexpr const char* LOS = "Los ";
static constexpr const char* ANGELES = "Angeles";
};
如何创建另一个常量字符串(const char*
或const std::string
)作为两个常量字符串的连接?添加以下行
static constexpr const std::string LOS_ANGELES = std::string(LOS).append(ANGELES);
发出错误:
error: the type ‘const string {aka const std::basic_string<char>}’ of constexpr variable ‘Test::LOS_ANGELES’ is not literal
不能实例化constexpr std::string
。
cppreference声明,对于c++ 11, constexpr
变量要求其类型为LiteralType。LiteralType有一个平凡的析构函数,但是std::string
的析构函数不是平凡的。
可以使用宏。这是丑陋的,但它工作。
#define MLOS "Los "
#define MANGELES "Angeles"
class Test
{
public:
static constexpr const char* LOS = MLOS;
static constexpr const char* ANGELES = MANGELES;
static constexpr const char* LOSANGELES = MLOS MANGELES;
};
也许这个答案对你有帮助。
我不相信std::string的构造函数是constexpr,所以我认为这是不可能的。但是,您可以模拟它:
template<int LENGTH>
struct CES {
static constexpr auto size = LENGTH;
char data[LENGTH];
};
template<int N>
constexpr auto make_ces(const char (&v)[N]) {
CES<N-1> result {};
for (int i = 0; i < N-1; ++i) {
result.data[i] = v[i];
}
return result;
}
template<int L1, int L2>
constexpr CES<L1+L2> operator+(const CES<L1>& x, const CES<L2>& y) {
CES<L1+L2> result{};
for (int i = 0; i < L1; ++i) {
result.data[i] = x.data[i];
}
for (int i = 0; i < L2; ++i) {
result.data[L1+i] = y.data[i];
}
return result;
}
constexpr auto LOS = make_ces("Los");
constexpr auto ANGELES = make_ces("Angeles");
constexpr auto LOS_ANGELES = LOS + ANGELES;
static_assert(LOS_ANGELES.data[2] == 's', "ok");
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 这两个C++语句连接字符串有什么区别?
- 两个字符串之间的数学运算
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如何在 main 函数中输出两个新字符串C++?
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)