Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic template non-type arguments

Tags:

c++

templates

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;
like image 722
Benjy Kessler Avatar asked Feb 05 '13 15:02

Benjy Kessler


2 Answers

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.

like image 119
David Rodríguez - dribeas Avatar answered Sep 22 '22 12:09

David Rodríguez - dribeas


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.

like image 22
TemplateRex Avatar answered Sep 19 '22 12:09

TemplateRex