I want my class to receive a non-type template argument but I don't want to specify the type of the non-type argument. I can do this by writing:
template<class Type, Type param>
class A
{};
It can then be used as follows:
A<int,3> a;
This is redundant because once I know that param = 3
then I know that Type = int
. Is there any way of writing this so that all of the following lines compile and instantiate different types?
A<3> a;
A<3.0> b;
A<3.0f> c;
No, that cannot be done. The type of all non-type template arguments must be defined in the parameter, and can never be inferred from the use, i.e. you need Type
to be known when the compiler analyzes the argument Type param
.
If A
is a function object, you could do either put a function template member inside a regular clas
class A
{
public:
template<class Type>
void operator()(Type param) { }
};
or wrap a class template inside a function template
template<class Type>
class A
{
public:
void operator()(Type param) { }
};
template<class Type>
void fun(Type param)
{
A<Type>()(param);
}
and calling it as A()(3)
or fun(3)
will deduce Type
to be int
, and similar for the others. This is because function templates DO have their arguments deduced, but not so for class templates. So if you use your class template A
for other purposes than a function object, you need to specify its arguments.
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