相关疑难解决方法(0)

为什么字符串文字是l值,而所有其他文字都是r值?

C++ 03 5.1主要表达式
§2:

文字是主要表达方式.它的类型取决于它的形式(2.13).字符串文字是左值; 所有其他文字都是右值.

这背后的理由是什么?
据我所知,字符串文字是对象,而所有其他文字都不是.并且l值总是指对象.

但问题是为什么字符串文字是对象,而所有其他文字都不是?
这个理由在我看来更像是鸡蛋或鸡肉问题.

我理解这个问题的答案可能与硬件架构有关,而不是C/C++作为编程语言,但我想听到同样的看法.

注意:我将此问题标记为c&c ++,因为C99标准也有类似的引用,特别是§6.5.1.4

c c++ literals string-literals

53
推荐指数
4
解决办法
5760
查看次数

使用const char*作为非类型参数的模板技巧

我非常清楚直接传递const char*作为模板的非类型参数是错误的,因为在两个不同的转换单元中定义的两个相同的字符串文字可能具有不同的地址(尽管大多数情况下编译器使用相同的地址).可以使用一个技巧,请参阅下面的代码:

#include <iostream>

template<const char* msg>
void display()
{
    std::cout << msg << std::endl;
}

// need to have external linkage 
// so that there are no multiple definitions
extern const char str1[] = "Test 1"; // (1)

// Why constexpr is enough? Does it have external linkage?
constexpr char str2[] = "Test 2";    // (2)

// Why doesn't this work? 
extern const char* str3 = "Test 3";  // (3) doesn't work

// using C_PTR_CHAR = const …
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++11

21
推荐指数
1
解决办法
7316
查看次数

标签 统计

c++ ×2

c ×1

c++11 ×1

constexpr ×1

literals ×1

string-literals ×1

templates ×1