C++ 非类型模板参数不引用任何声明? #包括 #包括 使用名称空间std; 模板 结构SomeClass{}; 结构S1 { typedef int类型; 地层类型; }; int main(){ x类; }
失败,并显示以下消息:C++ 非类型模板参数不引用任何声明? #包括 #包括 使用名称空间std; 模板 结构SomeClass{}; 结构S1 { typedef int类型; 地层类型; }; int main(){ x类; },c++,templates,C++,Templates,失败,并显示以下消息: g++temp.cc-o temp-std=c++14 cc:18:20:错误:非类型模板参数未引用任何声明 x类; ^~~~~~~~~~~~~ temp.cc:8:24:注意:此处声明了模板参数 typename T::strata&X> 为什么它适用于int而不适用于str
g++temp.cc-o temp-std=c++14
cc:18:20:错误:非类型模板参数未引用任何声明
x类;
^~~~~~~~~~~~~
temp.cc:8:24:注意:此处声明了模板参数
typename T::strata&X>
为什么它适用于int而不适用于string?
为什么说字符串是非类型参数?作为值而不是类型或模板的模板参数称为“非类型模板参数” 此操作因引用而失败。如果有
typename T::type&N
,则在3
上会出现类似错误
引用
实例化具有非类型模板参数的模板时,以下限制适用:
- 对于左值引用参数,实例化时提供的参数不能是临时的、未命名的左值或没有链接的命名左值(换句话说,参数必须有链接)
g++ templ.cc -o templ -std=c++14
templ.cc:18:20: error: non-type template argument does not refer to any declaration
SomeClass<S1, 3, string("erg")> x;
^~~~~~~~~~~~~
templ.cc:8:24: note: template parameter is declared here
typename T::strata& X>
标准:字符串erg(“erg”);
int main(){
x类;
}
因为它不是一种类型。非类型参数仅限于原语(实际上是整数和指针)@这里使用的类类型的PasserBy引用也是允许的。。。我没有看到那个参考:)这段代码闻起来像地狱一样可疑。理想情况下,您希望实现什么?如果我将字符串放入main()中,为什么它会抱怨“没有链接”?因为具有自动存储持续时间的变量没有链接。
g++ templ.cc -o templ -std=c++14
templ.cc:18:20: error: non-type template argument does not refer to any declaration
SomeClass<S1, 3, string("erg")> x;
^~~~~~~~~~~~~
templ.cc:8:24: note: template parameter is declared here
typename T::strata& X>
std::string erg("erg");
int main () {
SomeClass<S1, 3, erg> x;
}