开发者

Why can't template non type parameters be of class type

class E开发者_如何学Pythonxample {

   // ...
};

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

   // ...
};

My question is why can't template non-type parameters be of class type?

The error that I get is

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


Simply, because those are the rules. Rationally, template parameters have to be resolved at compile time and objects of class type are only constructed (even temporaries and those with static storage duration) at run time. You can only have template parameters that are "values" resolvable at compile time such as integers and types. It is possible to have template parameters that are pointers or references to objects, though.


According to 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. 

It is obvious that any std conforming compiler throws an error if you declare class as non type template argument.


Starting with C++ 20 this is now supported

The classes generally need to be a Literal Type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜