微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

class A;
class B;

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

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

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


解决方法

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

这是一个完整的演示,其中 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。