首先,我知道变量函数在c++中不能是虚的。我的问题是如何模仿下一个“不正确”的例子。我希望有一个类A和类B,它继承了它,只实现了“它的一部分”:
class A {
template<class... Types>
virtual void f(Types... buffers) { return; }
};
class B : public A {
// Overrides only 2 options of "generic" f
void f(unsigned char* buff2) override;
void f(unsigned char* buff1, unsigned int* buff2) override;
};
在我的用例中,有这个通用的f
调用非常重要,但是不同的类只支持可变函数f
的“子集”:
A* a= factory(...);
a->f(buff1, buff2, buff3); // OK
a->f(buff1); // OK
a->f(buff1, buff2); // Error! Factory gave an instance which does not support this call
3条答案
按热度按时间vpfxa7rd1#
你可以使用
std::variant
代替virtual,并使用重载作为分派:然后呢
Demo
tmb3ates2#
由于各种
f
函数除了它们的名称之外没有任何共同之处,所以我将它们建模为实际的独立接口,这与现有的OOP工具更好地结合在一起,这些工具可以处理可选地实现接口(即dynamic_cast
)。A
和它自己的f
模板只是隐藏了交叉转换和错误处理。See it live on Godbolt.org
3pmvbmvn3#
你好像在找
std::any
。然而,您的需求意味着一个可怕的设计问题。如果不知道
A
实际上是什么子类,那么给定A
的人就不知道他们可以用它做什么,此时他们应该有对该类型的引用。