在另一个问题的讨论中,我被给出了一个例子,其中标识符的关联性显然影响了它在常量表达式中的可用性:
上一个错误(使用GCC)的内容为:
extern char const a[] = "Alpha";
char constexpr b[] = "Beta";
char const g[] = "Gamma";
template <const char *> void foo() {}
auto main()
-> int
{
foo<a>(); // Compiles
foo<b>(); // Compiles
foo<g>(); // Doesn't compile
}
上一个错误(使用GCC)的内容为:
test.cc: In function 'int main()':
test.cc:12:13: error: the value of 'g' is not usable in a constant expression
foo<g>(); // Doesn't compile
^
test.cc:3:16: note: 'g' was not declared 'constexpr'
char const g[] = "Gamma";
^
在早期的讨论中,我可能错过了示例的重要性,因为我认为仅仅是链接使得foo<a>
与foo<g>
不同 - 但是,我开始怀疑这个观点。
- 真的是链接吗,还是
extern
提供的其他属性使foo<a>()
成为可能? - 允许
foo<a>()
而不允许foo<g>()
的原理是什么?特别是,如果它是由链接决定的,那么为什么内部链接会导致变量不能用作常量表达式,而相同的变量声明为extern
则可以使用? - 有人认为符号是否对链接器可见与此相关。对我来说,当添加
static
时仍允许foo<b>
变体的事实证明了这一点 - 或者我错了吗? - (
foo<b>()
和foo<g>()
之间的区别已经被其他问题充分解释了,我想)。
-std=c++1z
。 - T.C.