错误:模板可能不是“虚拟"的 [英] error: templates may not be 'virtual'
本文介绍了错误:模板可能不是“虚拟"的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够为基类MCFormater提供一种适用于不同类型(uint32,uint8 ...)的格式化方法
I would like to be able to provide to the base class MCFormater a formatting method that would work for different types (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;
}
};
但是我得到了错误:模板可能不是虚拟"的.正确的方法是什么?(有吗?)
but I get the error: templates may not be 'virtual'. what is the right way to do it? (is there one?)
推荐答案
修改...
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函数调用时,链接器都必须向虚拟表中添加一个新条目.动态链接会让人难以接受.
Explanation: Member function templates cannot be virtual. If this was allowed then the linker would have to add a new entry to the virtual table every time the Format function was called with a different type. Dynamic linking would be unacceptably complicated.
这篇关于错误:模板可能不是“虚拟"的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文