我希望能够为基类MCFormater提供一种适用于不同类型的格式化方法(uint32,uint8 ...)
class MCFormater {
public:
MCFormater() {}
virtual ~MCFormater() {}
virtual mcc_t Gen();
protected:
template<typename K> //here is the problem
virtual void Format(K& a, const K& b) = 0;
//...
uint32_t a;
uint8_t b;
void Foo();
};
void MCFormater::Foo() {
Format<uint32_t>(a, 3); //I want to be able to call for Format
Format<uint8_t>(b, 3); //with uint32_t, and uint8_t, and more
}
class GFormater : public MCFormater {
GFormater() {}
template<typename K>
virtual void Format(K& a, const K& b) {
a = b;
}
};
class EFormater : public MCFormater {
EFormater() {}
template<typename K>
virtual void Format(K& a, const K& b) {
a |= b;
}
};
但我得到错误:模板可能不是'虚拟'。 什么是正确的方法呢? (有吗?)
答案 0 :(得分:2)
修改...
class MCFormater {
public:
MCFormater() {}
virtual ~MCFormater() {}
virtual mcc_t Gen();
protected:
template<typename K> //here is the problem
virtual void Format(K& a, const K& b) = 0;
//...
uint32_t a;
uint8_t b;
void Foo();
};
void MCFormater::Foo() {
Format<uint32_t>(a, 3);
Format<uint8_t>(b, 3);
}
class GFormater : public MCFormater {
GFormater() {}
template<typename K>
virtual void Format(K& a, const K& b) {
a = b;
}
};
class EFormater : public MCFormater {
EFormater(FTEKeeps* keeps) : MCFormater(keeps) {}
template<typename K>
virtual void Format(K& a, const K& b) {
a |= b;
}
};
要...
#include<iostream>
using namespace std;
template<typename K>
class MCFormater {
public:
MCFormater() {}
virtual ~MCFormater() {}
virtual mcc_t Gen();
protected:
virtual void Format(K& a, const K& b) = 0;
//...
uint32_t a;
uint8_t b;
void Foo();
};
template<typename K>
void MCFormater<K>::Foo() {
Format<uint32_t>(a, 3);
Format<uint8_t>(b, 3);
}
template<typename K>
class GFormater : public MCFormater<K> {
GFormater() {}
virtual void Format(K& a, const K& b) {
a = b;
}
};
template<typename K>
class EFormater : public MCFormater<K> {
EFormater(FTEKeeps* keeps) : MCFormater<K>(keeps) {}
virtual void Format(K& a, const K& b) {
a |= b;
}
};
说明:成员函数模板不能是虚拟的。如果允许,则每次使用不同类型调用Format函数时,链接器都必须向虚拟表添加新条目。动态链接会令人无法接受。