Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类中的非模板函数_C++_Function_Template Classes - Fatal编程技术网

C++ 模板类中的非模板函数

C++ 模板类中的非模板函数,c++,function,template-classes,C++,Function,Template Classes,我想知道是否有办法在模板类中放置非模板函数。 简单地说,我不想让编译器为每种类型重复该函数,因为该函数只操作指针,因此没有类型。这可能吗 所以如果你有这样的代码 template <typename T> class CLASS{ }; 模板 班级{ }; 然后,将针对每个类型T重复内的每个功能 我只是不想发生这种事 我想要一个对所有类型都是静态的函数,并且不会在内存中对每个类型重复。从基类继承该函数 class BASE_CLASS { public: static

我想知道是否有办法在模板类中放置非模板函数。 简单地说,我不想让编译器为每种类型重复该函数,因为该函数只操作指针,因此没有类型。这可能吗

所以如果你有这样的代码

template <typename T>
class CLASS{

};
模板
班级{
};
然后,将针对每个类型T重复内的每个功能 我只是不想发生这种事


我想要一个对所有类型都是静态的函数,并且不会在内存中对每个类型重复。

从基类继承该函数

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

template <typename T>
class CLASS: public BASE_CLASS {

};
class基类{
公众:
静态void非模板化函数();
};
样板
类:公共基类{
};

我假设您的问题是这样的:

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. */
  };
};
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. */);
  };
};
模板
结构Foo{
//..
空条(){
/*这里的大多数或所有代码对于所有T都是相同的,
并且不使用依赖于T的任何东西*/
};
};
您希望定义“bar”的方式是,只有一个bar函数,而不是“Foo”的每个实例化都有一个,也就是说,您不希望
Foo::bar
是与
Foo::bar
不同的函数

这是无法做到的,因为“bar”函数是类模板的成员,因此也是其每个实例化的成员

相反,您可以而且应该做的是定义一个helper(free)函数,该函数中包含所有“对所有T相同”的代码。大概是这样的:

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. */
  };
};
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. */);
  };
};
名称空间{
void Foo\u bar\u帮助程序(/*..*/){
/*通用代码在这里*/
};
};
样板
结构Foo{
//..
空条(){
Foo_bar_helper(/*在此处传递Foo的“内脏”。*/);
};
};
通常情况下,bar函数将由编译器内联,真正剩下的只是Foo对象(如果有的话)的“guts”的扩展,作为helper函数的参数(可以根据需要使用或不使用外部链接来实现)


另一种选择是从非模板基类继承,但我个人不喜欢对这类东西使用继承,而且您仍然需要对Foo对象(如果有的话)的“内脏”进行相同的转发。

您已经尝试过了吗?模板类的所有成员函数都是非模板的,除非它们是用
模板
本身声明的。但这可能并不完全是您要问的。若您有类似于这个模板类对象{}的代码,那个么其中的每个函数对于每种类型的Classic都是重复的。若您发布代码并准确地告诉我们您的问题所在,那个么它会更好。