错误:模板可能不是“虚拟"的

编程入门 行业动态 更新时间:2024-10-24 22:26:55
本文介绍了错误:模板可能不是“虚拟"的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够为基类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.

更多推荐

错误:模板可能不是“虚拟"的

本文发布于:2023-08-04 03:20:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   错误   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!