为什么模板非类型参数不能是类类型

时间:2010-11-05 07:30:12

标签: c++ templates types

class Example {

   // ...
};

template <typename T, Example ex>  //Error
class MyExample{

   // ...
};

我的问题是为什么模板非类型参数不能是类类型?

我得到的错误是

error: ‘class Example’ is not a valid type for a template constant parameter

3 个答案:

答案 0 :(得分:15)

简单地说,因为那些是规则。理所当然,模板参数必须在编译时解析,并且类型的对象仅在运行时构建(甚至临时和具有静态存储持续时间的对象)。您只能在编译时具有可以解析的“值”的模板参数,例如整数和类型。但是,可以使用指针或对象引用的模板参数。

答案 1 :(得分:6)

根据c++ standard

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. 

很明显,如果将类声明为非类型模板参数,任何符合标准的编译器都会抛出错误。

答案 2 :(得分:1)

从 C++ 20 开始,现在支持。

相关问题