【发布时间】:2025-11-28 00:35:01
【问题描述】:
我已经开发了以下代码来尝试实现非虚拟多态性:
#include <functional>
#include <iostream>
namespace{
using std::function;
class base {
protected:
using signiture =void(void);
using func_t = function<signiture>;
~base(){}
public:
func_t bar;//std::function object to a function of type "signature"
};
}
template <typename implementation>
class foo:public base {
public:
foo(implementation* instance){
bar = func_t(std::bind(&implementation::bar_implementation,instance));
//binds a function of name "bar_implementation" from class implementation to the std::function object
//binds to object "instance"
}
};
typedef base foo_base;
class testcase:public foo<testcase> {
public:
friend class foo;//allows implementations to be protected or private
testcase():foo(this){}//sends instance to the constructor of the base class in order to enable binding
protected:
void bar_implementation(void){
std::cout<<"Hello"<<std::endl;
}
};
class testcase2:public foo<testcase2> {
public:
friend class foo;//allows implementations to be protected or private
testcase2():foo(this){}
protected:
void bar_implementation(void){
std::cout<<"World!"<<std::endl;
}
};
int main(int argc, const char * argv[]) {
testcase t;
testcase2 t2;
foo_base* b = &t;
foo_base* b2 = &t2;
b->bar();
b2->bar();
return 0;
}
实际上,这段代码分散在几个文件中...
我想知道我的代码中的任何内容是否可以被视为不良做法、未定义的行为或在某些庄园中是不受欢迎的? A Live Example
对这种模式作为虚拟继承和设计的替代品的任何想法都值得赞赏。
如果我能澄清任何事情,请告诉我。
编辑: 我问这个问题是为了确定这样的设计是否有任何理由可以成为实现非虚拟多态性的合适方法,如果不是,为什么会这样?
【问题讨论】:
-
问题:这段代码真的不是虚表多态,还是你自己滚?
-
考虑到
std::function在后台使用虚函数(擦除类型),我看不出这应该完成什么。 -
base::bar在大多数实际用途中是一个单条目 vtable(只是调用成本更高)。练习的重点是什么? -
看起来您正在竭尽全力实现语言本身已经实现的东西,只有该语言可能更有效、更安全地实现它。
-
我认为部分问题在于这看起来不像是“非虚拟”的东西。它看起来像一个虚拟函数调用系统的手动实现。
标签: c++ inheritance c++11 polymorphism