ZweeBugg
ZweeBugg

Reputation: 61

class template vs. member template

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

Answers (2)

Yam Marcovic
Yam Marcovic

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.

  1. Like you said, if you have a member variable of type T, your class needs to be a template.
  2. If you have a function returning 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.
  3. If you need a virtual function that depends on T, your class needs to be a template.
  4. If you need a different class layout (i.e. member variables) per instantiation of T, your class needs to be a template.
  5. If you need to make sure that your functions all operate on a single type rather than generate different versions of them arbitrarily, 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

Pete Becker
Pete Becker

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

Related Questions