Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a template class without a template argument

Tags:

c++

templates

I have a Visual Studio 2008 C++ project with a template class that takes the templated value in the constructor like this:

template< typename A >
struct Foo
{
    const A& a_;
    Foo( const A& a ) : a_( a ) { };
};

Therefore, I have to construct this class like this:

int myval = 0;
Foo< int > foo( myval );

It seems redundant to have to specify int as a template parameter when it's already specified in the constructor. I'd like some way to use it like this:

Foo foo( myval );

As is, I get the compiler error:

error C2955: 'Foo' : use of class template requires template argument list

Thanks, PaulH

like image 793
PaulH Avatar asked Dec 04 '22 08:12

PaulH


1 Answers

C++17 fixed this issue, introducing template argument deduction for constructors.

Citing Herb Sutter:

[...] you can write just pair p(2, 4.5); instead of pair<int,double> p(2, 4.5); or auto p = make_pair(2, 4.5);. This is pretty sweet, including that it obsoletes many “make” helpers.

like image 120
Fabio A. Avatar answered Dec 28 '22 04:12

Fabio A.