gpt4 book ai didi

c++ - const 变量作为非类型模板参数(VARIABLE 不能出现在常量表达式中)

转载 作者:可可西里 更新时间:2023-11-01 17:52:21 26 4
gpt4 key购买 nike

为什么会这样?

char __nontype[] = "foo";
typedef TemplateClass<T, __nontype> MyClass;

但这(带有常量变量)不是吗?

const char __nontype[] = "foo";
typedef TemplateClass<T, __nontype> MyClass;

编译器错误:

错误:‘__nontype’不能出现在常量表达式中

错误:模板参数 2 无效

最佳答案

区别是因为 const 影响链接。如果您添加 extern,它会起作用。也就是说,据我所知:

14.3.2 Template non-type arguments [temp.arg.nontype]

A template-argument for a non-type, non-template template-parameter shall be one of:

  • an integral constant expression (including a constant expression of literal class type that can be used as an integral constant expression as described in 5.19); or
  • the name of a non-type template-parameter; or
  • a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or
  • a constant expression that evaluates to a null pointer value (4.10); or
  • a constant expression that evaluates to a null member pointer value (4.11); or
  • a pointer to member expressed as described in 5.3.1.

它也应该在没有 extern 的情况下工作。允许该对象具有内部链接,但您的编译器尚不支持。这是C++11的变化之一,之前的C++标准是不允许的。

关于c++ - const 变量作为非类型模板参数(VARIABLE 不能出现在常量表达式中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com