你如何在子类中重载模板化函数(专用)?

Ale*_*lex 3 c++ templates

我有一个带有模板化函数的基类,它具有一般模板类型,以及专用版本.

#ifndef BASE_CLASS
#define BASE_CLASS

#include <iostream>

using namespace std;

struct Type1
{
};

struct Type2
{
};

class baseClass
{
    public:
    template<class Type>
    void doStuff(Type & t)
        {
        templateFunction(t);  
        }

    template<class Type>
    void templateFunction(Type & t);
};

template<class Type>
void baseClass::templateFunction(Type & t)
{
    cout << "This is the generic function!" << endl;
}

template<>
void baseClass::templateFunction(Type1 & t)
{
    cout << "This is the specialized function: - Type1" << endl;
}
#endif
Run Code Online (Sandbox Code Playgroud)

我还有一个继承自"baseClass"的子类.但是,子类需要不同的专业化功能.

#ifndef CHILD_CLASS
#define CHILD_CLASS

#include "BaseClass.h"

class ChildClass : public baseClass
{
    public:

};

template<>
void ChildClass::templateFunction(Type1 & t)
{
    cout << "We overloaded the specialized template function for type 1!" << endl;
}

#endif
Run Code Online (Sandbox Code Playgroud)

以上不编译:

ChildClass.h:13:错误:没有在âChildClass中声明的成员函数âtemplateFunctionâ:ChildClass.h:13:错误:函数声明无效

如果我将"重载"功能更改为:

template<>
void baseClass::templateFunction(Type1 & t)
{
    cout << "We overloaded the specialized template function for type 1!" << endl;
}
Run Code Online (Sandbox Code Playgroud)

我得到:ChildClass.h:13:错误:重新定义âvoidbaseClass:: templateFunction(Type&)[Type = Type1]âBaseClass.h:36:错误:âvoidbaseClass:: templateFunction(Type&)[Type = Type1] â先前在这里宣布

如何正确地重载子类中的专用模板函数?

供参考,主要:

#include "BaseClass.h"
#include "ChildClass.h"

int main()
{
    Type1 first;
    Type2 second;

    baseClass theBaseClass;
    ChildClass theChildClass;


    theBaseClass.doStuff(first);
    theBaseClass.doStuff(second);

    theChildClass.doStuff(first);
    theChildClass.doStuff(second);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

根据以下建议:Kerrek SB,我已将ChildClass更改为:

#ifndef CHILD_CLASS
#define CHILD_CLASS

#include "BaseClass.h"
class ChildClass : public baseClass
{
    public:
    template<class Type>
    void templateFunction(Type & t);
};

template<>
void ChildClass::templateFunction(Type1 & t)
{
    cout << "We overloaded the specialized template function for type 1!" << endl;
}

#endif
Run Code Online (Sandbox Code Playgroud)

输出:

This is the specialized function: - Type1
This is the generic function!
This is the specialized function: - Type1
This is the generic function!
Run Code Online (Sandbox Code Playgroud)

我希望:

This is the specialized function: - Type1
This is the generic function!
We overloaded the specialized template function for type 1!
This is the generic function!
Run Code Online (Sandbox Code Playgroud)

所以这仍然不起作用.

bar*_*gol 5

它仍然无法按您希望的方式工作的原因是该函数在父类中不是虚拟的.但是,不可能具有虚拟模板功能.

我看到两个主要选择:

  • 正如rhalbersma建议的那样,使类本身模板,然后覆盖子类中所需的方法(现在不是模板).
  • 对于专门的方法,只需编写一个具有不同名称的新方法,它可以满足您的需要.

但我相信有人会想出更好的主意...... =)