vendredi 6 mai 2016

How to make template type deduction work with reference?

I have a template function func :

template<typename T>
void func(T p)  { f(p); }

and a set of functions f :

f(SomeType&);
f(int);
...

If I instantiate the template function func, using a reference as function argument p, without explicitely specifying template parameter T, then the type deduced will not be the reference type of p but rather the type p is a reference to, e.g. :

SomeType s;
SomeType& ref_to_s = s;
func(ref_to_s);             // type deduction results in: func<SomeType>(ref_to_s)
func<SomeType&>(ref_to_s);  // need to explicitely specify type to work with reference

So, my questions are:

  • Why does compiler fail to deduce the reference type SomeType& in the above situation ?
  • Is there any way to define template function func, so that type deduction works with a reference type, without explicit specification of the template parameter T ?

To be clear, I'd like something working with both (see functions f above):

func(ref_to_s);    // calls func<SomeType&>(ref_to_s)
func(1);           // calls func<int>(1)

Aucun commentaire:

Enregistrer un commentaire