Sometimes it works sometimes not:
template
void f(T t) {}
template
class MyClass {
public:
MyClass(T t) {}
};
void test
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) {}
void print(){
std::cout<<"try MyClass"<<std::endl;
}
};
template <typename T>
MyClass<T> MakeMyClass(T t) { return MyClass<T>(t); }
and then call auto a = MakeMyClass(5);
to instantiate the class.
Read up on Template Argument Deduction (and ADL or Koenig lookup).
In C++17, it is possible to infer some types using auto
, though the template parameters still need to be specified here:
#include <iostream>
#include <string>
template <class T1,class T2>
auto print_stuff(T1 x, T2 y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
print_stuff(3,"Hello!");
print_stuff("Hello!",4);
return 0;
}
Using the -fconcepts flag in gcc, it is possible to infer the parameters, though this is not yet a part of the C++ standard:
#include <iostream>
#include <string>
auto print_stuff(auto x, auto y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
print_stuff(3,"Hello!");
print_stuff("Hello!",4);
return 0;
}