jms*_*jms 7 c++ string c-strings constexpr c++11
返回整数文字副本的函数
int number()
{ return 1; }
Run Code Online (Sandbox Code Playgroud)
可以使用关键字轻松转换为普通的编译时表达式constexpr.
constexpr int number()
{ return 1; }
Run Code Online (Sandbox Code Playgroud)
但是,当涉及到字符串文字时,我会感到困惑.通常的方法是返回指向const char字符串文字的指针,
const char* hello()
{ return "hello world"; }
Run Code Online (Sandbox Code Playgroud)
但我认为仅仅改变"const" constexpr并不是我想要的(作为奖励,它还会产生编译器警告,使用gcc 4.7.1 将不推荐的从字符串常量转换为'char*')
constexpr char* hello()
{ return "hello world"; }
Run Code Online (Sandbox Code Playgroud)
有没有办法以hello()这样的方式实现调用在下面的示例中用常量表达式替换?
int main()
{
std::cout << hello() << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*our 10
const而constexpr在不能互换,你的情况,你不想放弃的const,但你要添加constexpr像这样:
constexpr const char* hello()
{
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
当你放下你收到警告const,是因为文字字符串是array of n const char等一个指向字符串字面量应该是*为const char**但在Ç一个字符串常量是char类型的数组,即使它是不确定的行为尝试为了修改它们,它被保留以便向后兼容,但是被折旧以便应该避免.
| 归档时间: |
|
| 查看次数: |
6831 次 |
| 最近记录: |