PaulH PaulH - 1 year ago 127
C++ Question

using a template class without a template argument

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
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


Answer Source

If you name the type at all, it has to be the complete type (i.e., Foo<int> and not just Foo).

A class can have multiple constructors or may have no constructors that have a parameter of the class template's type parameter, so there's no way to make this work for all class templates (in my opinion it would be confusing to have this work sometimes but not all the time).

If you are okay not naming the type at all, you can write a MakeFoo<T>() function template that constructs a Foo<T> and use function template argument deduction:

template <typename A>
Foo<A> MakeFoo(const A& a) { return Foo<A>(a); }

This pattern is commonly used in C++ (see, for example, make_shared).

If you want to store the returned object in a variable, though, that variable still needs to have a type. If you are able to move to a compiler that supports C++0x's auto (like Visual C++ 2010), then you can use that. Otherwise, you can use a third-party solution like BOOST_AUTO or write your own (though that would likely be quite a lot of work (-: ).

With auto, your code would look like:

auto foo(MakeFoo(myval));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download