У меня есть базовый класс с шаблонной функцией, который имеет общий шаблонный тип, а также специализированную версию.
#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
У меня также есть дочерний класс, который наследуется от "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
Выше не компилируется:
ChildClass.h: 13: ошибка: нет функции-члена templateFunction, объявленной в ChildClassâ
ChildClass.h: 13: ошибка: недопустимое объявление функции
Если я изменю «перегруженную» функцию на:
template<>
void baseClass::templateFunction(Type1 & t)
{
cout << "We overloaded the specialized template function for type 1!" << endl;
}
Я получаю:
ChildClass.h: 13: ошибка: переопределение пустого baseClass :: templateFunction (Type &) [with Type = Type1]
BaseClass.h: 36: ошибка: исключить baseClass :: templateFunction (Type &) [with 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;
}
По предложению: 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
Выход:
This is the specialized function: - Type1
This is the generic function!
This is the specialized function: - Type1
This is the generic function!
Я надеялся на:
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!
Так что это все еще не работает.