5

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;
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
  • @R.MartinhoFernandes I got 6 squares on my screen in your comment. wears his robe and wizard hat. – Aniket Inge Feb 05 '13 at 15:26
  • 1
    @Aniket I need a filler for the minimum of 15 characters requirement. I use bananas http://i.stack.imgur.com/DvRWZ.png because SO counts each one as two characters. – R. Martinho Fernandes Feb 05 '13 at 15:28

2 Answers2

5

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.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
1

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • Thanks, I don't use A as a function object, but that's good to know for the future. – Benjy Kessler Feb 05 '13 at 15:51
  • @BenjyKessler I updated it slightly because the function template can both be inside or outside the class. The difference between class and function templates is largely historical, see e.g. this [question](http://stackoverflow.com/q/11968994/819272) for a related aspect. – TemplateRex Feb 05 '13 at 16:19