我需要有关运算符重载和继承的帮助。
{{1}}
我希望能够做到这样的事情。问题在于运营商的争论。我想只能参加B班的B,但我不能因为原来的超载。我该如何解决这个问题?
答案 0 :(得分:0)
运算符只是函数,因此您的问题与它们无关。你想要的是多重派遣(双重,在这种特殊情况下,正如基督教正确提到的那样)。在实现和运行时复杂性方面有多种方法,包括需要语言支持的方法(参见例如虚函数参数和Bjarne Stroustrup的相应论文)。
如果您想在核心C ++中执行此操作,欢迎您查看我的通用实现并复制所需内容: https://ideone.com/uGue2K
代码的使用:
// C inherits from A, both have a static initializer that registers them and their base class(es)
struct print : Visitor2<A>
{
// Feel free to change the return type, but keep it consistent.
// Alternatively, you can call a lambda with the result.
static void v1(const A& a1, const A& a2, int i, int j)
{
std::cout << "A, A: "<< a1() << a2() << " " << i << " " << j << std::endl;
}
static void v2(const C& c1, const A& a2, int i, int j)
{
std::cout << "C, A: "<< c1() << a2() << " " << i << " " << j << std::endl;
}
// and so on...
print(int k_)
: k(k_)
{
add_visitor( v1, v2 /* ... */ );
}
auto operator[](const A& a) { /* see in code */ };
};
int main()
{
print p(4); // p takes virtual A&, virtual A&, int, int.
const A& a = A();
const A& b = B();
p[a][a](1, 2);
p[c][a](2, 3);
}
欢迎建议代码和模式。为了便于理解,访问者operator[](const A&)
就地实施,但可以完全在Visitor2<A>
中完成。
请注意,当有多个外部匹配并且首先尝试的内部匹配失败时,您不能只用Visitor< Visitor<A> >
代替Visitor2<A>
,因为它不会“回溯”到外部解析器。这凸显了多次发送的难度(Christian提到):您需要全局查看所有潜在功能。期待缓慢和大型编译单位;只有在规格中没有找到快捷方式才能实现。