Reputation: 61
Is there a good rule when to use a class template instead of using member templates? As I understand it, your are forced to use a class template if your class contains member variable templates but otherwise you are free of choice since this:
template<typename T>
class Foo
{
public:
void someMethod(T x);
};
behaves like this:
class Foo
{
public:
template<typename T>
void someMethod(T x);
};
Is my claim wrong? Or is there any rule of thumb when to use what?
Upvotes: 4
Views: 410
Reputation: 8141
You can choose to make your class a template, rather than having member function templates, for several reasons. Say you have a template parameter T
.
T
, your class needs to be a template.T
and not accepting T
, and you don't want to manually specify the type in each invocation, your class needs to be a template.T
, your class needs to be a template.T
, your class needs to be a template.The best rule of thumb would be to use the simplest thing that makes sense. In general, member function templates tend to be more rare—and virtually non-existent for the use case you're talking about. Maybe that's no coincidence.
Upvotes: 3
Reputation: 76315
The two are not at all the same. With the first:
Foo<int> f;
f.someMethod('a');
the called function is someMethod(int)
.
With the second:
Foo f;
f.someMethod('a');
the called function is someMethod(char)
.
Upvotes: 5