Possible Duplicate:
using a template class without a template argument
If I have a templated function, I don’t need to instantiate it, since it can be inferred from the arguments, like so:
template<typename T> void MyFunc(T arg);
int x;
MyFunc(x);
Is this true for any scenario where the compiler can guess the template parameters? Specifically, I am thinking of this:
template<typename T>
class MyClass {
public:
MyClass(T) { }
};
int x;
MyClass<int> c1(x); // regular style
MyClass c2(x); // is this allowed?
Yes and no.
The compiler doesn’t deduce types for class template parameters, but does allow defaults, so if you’re using
intquite a bit for this template, you could do:Note that this only works for one particular type per template though. It’s not choosing the type based on the type of parameter you supply, just using the default you’ve specified for the template, is you didn’t specify a type but passed (say) a
double, the template above would still instantiate overint, notdouble.Since the compiler can/will deduce template parameters for function templates, you can also create a small template function and use
auto: