一个返回整数字面值副本的函数。
有没有一种方法可以实现
int number()
{ return 1; }
使用关键字constexpr
可以轻松将其转换为普通的编译时表达式。
constexpr int number()
{ return 1; }
然而,当涉及到字符串字面值时,我开始感到困惑。通常的方法是返回一个指向字符串字面值的const char
类型指针。
const char* hello()
{ return "hello world"; }
但我认为仅仅将 "const" 改为 constexpr
并不是我想要的(作为奖励,它还会在使用 gcc 4.7.1 时产生编译器警告 deprecated conversion from string constant to 'char*')
constexpr char* hello()
{ return "hello world"; }
有没有一种方法可以实现
hello()
,使得在下面的示例中,调用被替换为常量表达式?int main()
{
std::cout << hello() << "\n";
return 0;
}
constexpr
数组呢?在constexpr const char* ptrToLiteral = "hello";
和constexpr char cstring[] = "hello";
之间,在底层有什么区别吗?如果有的话,是什么?后者以不同的方式存储吗? - jmscstring
是一个可修改的数组,它将被初始化为字符串字面值"hello"
的副本,而第一种情况ptrToLiteral
只是指向一个字符串字面值。 - Shafik Yaghmourcstring
被定义为constexpr
,因此它不应该被修改,试图像cstring[0] = 'a';
这样修改cstring
预期会导致错误 _assignment of read-only location 'cstring[0]'_。 - jmscstring
不可修改,因为它是一个constexpr
,但在其他情况下则可以修改。 - Shafik Yaghmour