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
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.
Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With