tags:

views:

326

answers:

2

Sometimes it works sometimes not:

template <class T> 
void f(T t) {}

template <class T>
class MyClass {
public:
  MyClass(T t) {}
};

void test () {
  f<int>(5);
  MyClass<int> mc(5);
  f(5);
  MyClass mc(5); // this doesn't work
}

Is there a way to hack around the example above? I.e. force the compiler to infer the template parameter from constructor parameter.

Will this be fixed in the future, or is there a good reason not to?

What is the general rule when compiler can infer template parameter?

+11  A: 

Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters

So it can be inferred here:

template <typename T>
void f(T t);

template <typename T>
void f(std::vector<T> v);

but not here:

template <typename T>
T f() {
  return T();
}

And not in class templates.

So the usual solution to your problem is to create a wrapper function, similar to the standard library function std::make_pair:

template <class T>
class MyClass {
public:
  MyClass(T t) {}
};

template <typename T>
MyClass<T> MakeMyClass(T t) { return MyClass(t); }

and then call MakeMyClass to instantiate the class.

jalf
+1, thorough. Minor nit: I suggest changing "when the parameter type is dependant" to "when a parameter type is dependent".
j_random_hacker
void f(typename T::const_iterator t); << here, T appears in a undeducible context. even when calling it with a vector<int>::const_iterator, for example, it won't be able to deduce vector<int> for T. the reason is that the meaning of ::const_iterator depends on T. but T again depends on the meaning of ::const_iterator. that's why boost::implicit_cast is coded like this: template<typename T> T implicit_cast(typename identity<T>::type t) { return t; } here again, we have an undeducible context.
Johannes Schaub - litb
Standard-ref is 14.8.2.4/4 (latest c++1x draft has it located at 14.9.2.5/5 - fixing also some of the shortcomings of the wording in the current standard). :) cheers
Johannes Schaub - litb
Duh, you're right, of course. Don't know what I was thinking.
jalf
+2  A: 

Read up on Template Argument Deduction (and ADL or Koenig lookup).

dirkgently