Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

class Example {

   // ...
};

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

like image 742
McGrath Avatar asked Nov 05 '10 07:11

McGrath


People also ask

Can we pass non-type parameters to templates?

Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.


1 Answers

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.

like image 142
CB Bailey Avatar answered Nov 08 '22 10:11

CB Bailey