boost 变体可以安全地与指向前向声明类的指针一起使用吗?

时间:2021-06-26 15:54:19

标签: c++ boost boost-variant

boost 变体能否安全地接受指向前向声明的类的指针,而不会产生任何意外影响,例如将它们与 visitors 一起使用?

class A;
class B;

typedef boost::variant<A*, B*> Variant;

class A {
public:
    A() {}
};

class B {
public:
    B() {}
};


1 个答案:

答案 0 :(得分:1)

我建议为此确切目的使用内置递归元素支持。它使(解除)分配自动且异常安全。

这是一个完整的演示,其中 B 实际上递归地包含一个 vector<Variant>(这是前向声明元素类型的 90% 的用例):

Live On Coliru

#include <boost/variant.hpp>
#include <iostream>
#include <iomanip>
struct A;
struct B;

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

struct A {
    int solution = 42;
};

struct B {
    std::string answer = "Thanks for all the fish!";
    std::vector<Variant> other { A{1}, A{2}, B{"Three", {}}, A{4} };
};

struct Visitor {
    std::string indent = " - ";
    void operator()(Variant const& v) const {
        boost::apply_visitor(Visitor{"  " + indent}, v);
    }
    void operator()(A const& a) const { std::cout << indent << a.solution << "\n"; };
    void operator()(B const& b) const {
        std::cout << indent << std::quoted(b.answer) << "\n";
        for (auto& v : b.other) {
            operator()(v);
        }
    };
};

int main()
{
    Variant v;
    v = A{};

    boost::apply_visitor(Visitor{}, v);

    v = B{};
    boost::apply_visitor(Visitor{}, v);
}

印刷品

 - 42
 - "Thanks for all the fish!"
   - 1
   - 2
   - "Three"
   - 4
相关问题