gpt4 book ai didi

c++ - boost 变体和访问者

转载 作者:行者123 更新时间:2023-11-30 02:23:31 24 4
gpt4 key购买 nike

我有 2 个结构 Base 和 Derived 以及 boost:variant 和 2 种类型。

struct Base : public boost::static_visitor<>
{
virtual void operator(Type1& t) {}
virtual void operator(Type2& t) {}
};

我想做的是将 Derived 定义为:

struct Derived : public Base
{
void operator(Type1& t) { /*some impl*/ }
};

我不会重写 Type2 的运算符,假设它在 Base 中定义并且为空。

出于某种原因,如果我写

Derived visitor;
boost::apply_visitor(visitor, variant);

我明白了错误:与“(Derived) (Type2&)”的调用不匹配

当然,如果我将 Type2 的运算符添加到派生中,它就可以正常工作。
谁能帮助理解为什么不为 Type2 添加运算符就无法正常工作?

最佳答案

名称查找不考虑基类中的运算符。您需要明确地将它放入 Derived 的范围内,以便通过名称查找看到它:

struct Derived : public Base
{
void operator()(Type1& t) { /*some impl*/ }
using Base::operator();
};

关于c++ - boost 变体和访问者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com