views:

144

answers:

2

Is there a way to have the compile deduce the template parameter automatically?

template<class T> 
struct TestA 
{
    TestA(T v) {} 
};
template<class T>
void TestB(T v)
{
}
int main()
{
    TestB (5);
}

Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"

+10  A: 

No, there isn't. Class templates are never deduced. The usual pattern is to have a make_ free function:

template<class T> TestA<T> make_TestA(T v)
{
    return TestA<T>(v);
}

See std::pair and std::make_pair, for example.

In C++0x you will be able to do

auto someVariable = make_TestA(5);

to avoid having to specify the type for local variables.

Sunlight
A: 

Sunlight is right, but if I may ask you a question: is that really a problem in your code. I mean:

TestA(5);

Would become

TestA<int>(5);

As long as it's only one template argument, it's not that bad, IMHO. It's not like you can get around typing the type once in most cases.

Leon Timmermans
Actually, that is really a problem, yes. In generic code, you often cannot spell out the type that easily.
MSalters