McG*_*ath 7 c++ templates types
class Example {
// ...
};
template <typename T, Example ex> //Error
class MyExample{
// ...
};
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么模板非类型参数不能是类类型?
我得到的错误是
error: ‘class Example’ is not a valid type for a template constant parameter
CB *_*ley 15
简单地说,因为那些是规则.理所当然,模板参数必须在编译时解析,并且类型的对象仅在运行时构建(甚至临时和具有静态存储持续时间的对象).您只能在编译时具有可以解析的"值"的模板参数,例如整数和类型.但是,可以使用指针或对象引用的模板参数.
小智 6
根据c ++标准,
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
— integral or enumeration type,
— pointer to object or pointer to function,
— reference to object or reference to function,
— pointer to member.
A non-type template-parameter shall not be declared to have floating point, **class**, or void type.
Run Code Online (Sandbox Code Playgroud)
很明显,如果将类声明为非类型模板参数,则任何符合标准的编译器都会抛出错误.