Isl*_*Cow 22 c++ inheritance templates
我想使用模板类为一些非常相似的子类提供一些常用功能.唯一的变化是每个使用的枚举.
这是父类
template<typename T> class E_EnumerationBase : public SimpleElement
{
public:
E_EnumerationBase();
virtual bool setValue(QString choice);
virtual T getState();
protected:
T state;
QHash<QString, T> dictionary;
};
template<typename T> E_EnumerationBase<T>::E_EnumerationBase() {
state = 0;
}
template<typename T> bool E_EnumerationBase<T>::setValue(QString choice) {
T temp;
temp = dictionary.value(choice, 0);
if (temp == 0) {
return false;
}
value = choice;
state = temp;
return true;
}
template<typename T> T E_EnumerationBase<T>::getState() {
return state;
}
Run Code Online (Sandbox Code Playgroud)
这是其中一个孩子
enum TableEventEnum {
NO_VALUE = 0,
ATTRACT = 1,
OPEN = 2,
CLOSED = 3
};
class E_TableEvent : public E_EnumerationBase<enum TableEventEnum>
{
public:
E_TableEvent();
};
Run Code Online (Sandbox Code Playgroud)
这是构造函数
E_TableEvent::E_TableEvent()
{
state = NO_VALUE;
dictionary.insert("attract", ATTRACT);
dictionary.insert("open", OPEN);
dictionary.insert("closed", CLOSED);
}
Run Code Online (Sandbox Code Playgroud)
链接器抛出此错误:
e_tableevent.cpp:6: error: undefined reference to `E_EnumerationBase<TableEventEnum>::E_EnumerationBase()'
Run Code Online (Sandbox Code Playgroud)
枚举可以用作这样的模板的参数吗?
spr*_*aff 35
枚举可以是模板参数,与int可以完全相同.
enum Enum { ALPHA, BETA };
template <Enum E> class Foo {
// ...
};
template <> void Foo <ALPHA> :: foo () {
// specialise
}
class Bar : public Foo <BETA> {
// OK
}
Run Code Online (Sandbox Code Playgroud)
但你根本没有提供定义 E_EnumerationBase::E_EnumerationBase()
这不是模板或继承的问题.就像你写这个一样:
struct Foo {
Foo ();
}
int main () {
Foo foo;
}
Run Code Online (Sandbox Code Playgroud)
语法用于值参数,就像typename参数一样.基本上,你只需要替换你typename的名字enum:
enum Foo { Bar, Frob };
template <Foo F> struct Boom {}; // primary template
template <> struct Boom<Bar> {}; // specialization of whole class
...
template <> void Boom<Frob>::somefun() {} // specialization of single member
Run Code Online (Sandbox Code Playgroud)