Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic class templates?

Tags:

c++

templates

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"


1 Answers

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.

like image 82
Sunlight Avatar answered Jun 28 '26 05:06

Sunlight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!