boost 变体可以安全地与指向前向声明 类 的指针一起使用吗?
Can boost variants safely be used with pointers to forward declared classes?
boost 变体能否安全地接受前向声明的指向 类 的指针,而不会产生任何意想不到的影响,例如将它们与 visitors 一起使用?
class A;
class B;
typedef boost::variant<A*, B*> Variant;
class A {
public:
A() {}
};
class B {
public:
B() {}
};
我建议为此目的使用内置的递归元素支持。它使(取消)分配自动且异常安全。
这是一个完整的演示,其中 B
实际上递归地包含一个 vector<Variant>
(这是前向声明元素类型用例的 90%):
#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
boost 变体能否安全地接受前向声明的指向 类 的指针,而不会产生任何意想不到的影响,例如将它们与 visitors 一起使用?
class A;
class B;
typedef boost::variant<A*, B*> Variant;
class A {
public:
A() {}
};
class B {
public:
B() {}
};
我建议为此目的使用内置的递归元素支持。它使(取消)分配自动且异常安全。
这是一个完整的演示,其中 B
实际上递归地包含一个 vector<Variant>
(这是前向声明元素类型用例的 90%):
#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