non template function in a template class [closed]

不想你离开。 提交于 2019-12-14 03:28:21

问题


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.


回答1:


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 {

};



回答2:


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



来源:https://stackoverflow.com/questions/27325794/non-template-function-in-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!