c++ - 带有自定义类的 boost 变体

标签 c++ boost-variant

我正在尝试使用自定义类boost-variant。我知道访问类内容的安全方法是使用boost::static_visitor。你知道为什么下面的代码不能编译吗?使用 boost::static_visitor 的签名/声明是否有任何要求?

我发现了这个问题Why can't I visit this custom type with boost::variant?但我没明白。

问候

AFG

#include <iostream>
#include <algorithm>
#include <boost/variant.hpp>

struct CA{};

struct ca_visitor : public boost::static_visitor<CA>
{
    const CA& operator()(const CA& obj ) const { return obj;}
};

struct CB{};

struct cb_visitor : public boost::static_visitor<CB>
{
    const CB& operator()(const CB& obj) const { return obj;}
};

int main(){   
    typedef  boost::variant< 
        CA  
        ,CB >  v_type;

    v_type v;
    const CA& a = boost::apply_visitor( ca_visitor(), v );
}

最佳答案

首先, boost::static_visitor<> 的模板参数应指定调用运算符返回的类型。在你的情况下,ca_visitor的调用运算符返回 CA const& ,不是CA .

但这还不是最大的问题。最大的问题是你似乎对如何 variant<> 有误解和static_visitor<>应该可以。

boost::variant<>的想法是它可以保存您在模板参数列表中指定的任何类型的值。您不知道该类型是什么,因此您为访问者提供了几个重载的调用运算符来处理每种可能的情况。

因此,当您提供访问者时,您需要确保它具有 operator() 的所有必要重载。接受类型 variant能把持住。如果您不这样做,Boost.Variant 会导致生成编译错误(这对您有好处,因为您忘记处理某些情况)。

这就是您面临的问题:您的访问者没有接受 CB 类型的对象的调用运算符.

这是正确使用 boost::variant<> 的示例和static_visitor<> :

#include <iostream>
#include <algorithm>
#include <boost/variant.hpp>

struct A{};
struct B{};

struct my_visitor : public boost::static_visitor<bool>
//                                               ^^^^
//                                               This must be the same as the
//                                               return type of your call 
//                                               operators
{
    bool operator() (const A& obj ) const { return true; }
    bool operator() (const B& obj) const { return false; }
};

int main()
{
    A a;
    B b;
    my_visitor mv;

    typedef boost::variant<A, B> v_type;

    v_type v = a;

    bool res = v.apply_visitor(mv);
    std::cout << res; // Should print 1

    v = b;

    res = v.apply_visitor(mv);
    std::cout << res; // Should print 0
}

关于c++ - 带有自定义类的 boost 变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15186527/

相关文章:

c++ - 将 32 位遗留代码移植到 64 位时如何处理不断变化的数据类型大小?

c++ - Clang 无法使用模板元编程编译参数包扩展

c++ - "Cannot convert parameter"使用 boost::variant 迭代器

c++ - 基类和模板

python - 尽管使用 -std=c++11 调用了编译器,但为什么 std::move 未定义?

c++ - 为什么 C4265 Visual C++ 警告(虚拟成员函数和无虚拟析构函数)默认关闭?

header 命名空间中的 C++ typedef 包含项找不到类型

c++ - 在 boost 变体中使用相同的数据类型

c++ - 嵌套提升变体类型以增加类型限制?

c++ - 带有 boost 变体递归包装器的字符串解析器