non template function in a template class

149 views Asked by At

I was wondering if there is a way to place a non template function within a template class. Simply put I don't want to compiler to repeat the function for each type since the function is only manipulating pointers hence there is no type. Is this possible?

so if you have code like this

template <typename T>
class CLASS{

};

then each function within will be repeated for each type T I simply don't want that to happen

I would like a function that is Static to all Types and there for does not repeat in memory for each individual type.

2

There are 2 answers

0
Ben On BEST ANSWER

Inherit the function from a base class

class BASE_CLASS {
public:
    static void not_a_templated_function();
};

template <typename T>
class CLASS: public BASE_CLASS {

};
0
Mikael Persson On

I assume that your problem is something like this:

template <typename T>
struct Foo {
  //..
  void bar() {
    /* most or all code here is the same for all T, 
       and uses nothing that depends on T. */
  };
};

And you would like the define "bar" in such a way that there will only be one bar function, not one for each instantiation of "Foo", i.e., you don't want Foo<int>::bar to be a different function from Foo<double>::bar.

This cannot be done, because the "bar" function is a member of the class template, and therefore, of each of its instantiations.

What you can and should do instead is to define a helper (free) function that has all the "same for all T" code in it. Something like this:

namespace {
  void Foo_bar_helper(/*..*/) {
    /* common code goes here. */
  };
};

template <typename T>
struct Foo {
  //..
  void bar() {
    Foo_bar_helper(/* pass the "guts" of Foo<T> here. */);
  };
};

Normally, the bar function will get inlined by the compiler and all that really remains is an expansion of the "guts" of the Foo object (if any) as parameters to the helper function (which you could implement with or without external linkage, as you wish).

Another option is to inherit from a non-template base class, but I personally don't like using inheritance for that kind of stuff, and you will still have to the same forwarding of the "guts" of the Foo object (if any).