[英]Why does the behavior of non-virtual methods (when called from derived classes) change if the base class has an/no additional virtual method(s)?
[英]Is it possible to use a derived class virtual method from a base class non-virtual method?
我有多个派生类,它们扩展了相同的 Base class。 它们具有相同的属性,除了可能具有不同 arguments 和主体的单个方法。 我怎样才能有一个 std::unique_ptr 并调用派生类的方法?
到目前为止,这是我所知道的:
virtual
的;这是我目前倾向于的(没有成功):
底座 class:
class IBase
{
/** ... **/
template <class T, typename ...Args>
MyCustomType perform(T &obj, Args ... args)
{
std::bind(obj->run, args);
}
virtual MyCustomType run(...) = 0;
};
派生 class:
class Derived : IBase
{
/** ... **/
virtual MyCustomType run(MyType1 a, MyType2 b, bool c) override
{
/* code */
}
};
我希望能够使用指向基础 class 的指针,调用basePtr->perform(a, b, c)
和子类Derived
中的方法来执行。 这有什么意义吗?
除了可能具有不同 arguments 和主体的单个方法
这不是 C++ 让您直接做的事情。 C++是一种静态类型语言; function 的调用者和被调用者必须静态地就传递的内容和返回的内容达成一致。 时期。
您尝试做的唯一选择是使用 static 类型擦除,例如std::any
或类似技术(例如将数据隐藏在void*
后面,但这非常危险)。 也就是说,您可以通过存储在any
中的值tuple
将“参数”传递给 function。 返回值也可以是any
。
但是,发送代码必须确切地知道接收代码期望什么,反之亦然; 在不确切知道您期望在那里的情况下,您无法打开any
包装。 所以接口是通用的,但是接收者和发送者仍然必须就到底发生了什么达成一致。
而且您绝对不希望接收 function 一遍又一遍地尝试一堆不同的转换来确定提供了哪组参数,从而确定要调用哪个 function 主体。
一般来说,您应该尽可能避免使用此类接口,因为错误和错误的可能性很高。
我想我对最初的想法有了一个可能的解决方案,使用Variadic Function Templates 。
class IBase
{
template <typename ... Args>
MyType run(Args... as)
{
MyType result;
return result;
}
};
然后我可以在Derived
中重载这个方法:
class Derived : IBase
{
/** ... **/
MyType run(const MyOtherType &X, const int &a);
};
谁能想到这个解决方案的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.