【问题标题】:how to set a value for parameter of type boost::varivant <A,B>* to be equal to some A*?如何将 boost::varivant <A,B>* 类型的参数的值设置为等于某个 A*?
【发布时间】:2020-03-23 08:48:24
【问题描述】:

说我有

class A {
};
class B {
};

using AOrB = boost::variant <A,B>;

A* ptr2a = ....
AOrB* another_ptr2a = a;//this doesn't compile for me, what is the correct way to do it?

使用 boost::variant* 是一种不好的做法吗?

【问题讨论】:

  • “使用 boost::variant* 是一种不好的做法吗?” ——几乎可以肯定。除此之外,您想要的根本无法完成:不能将A* 分配给A
  • variant&lt;A, B&gt;* != variant&lt;A*, B*&gt;.
  • variant&lt;A, B&gt; 包含AB,而不是A*。由于尚不清楚您实际想要实现什么,因此我投票决定关闭以进行澄清。

标签: c++ boost-variant


【解决方案1】:

你不能。 AOrBA 子对象或B 子对象组成,它们都不能指向现有的A,也不能从指向@ 的指针形成指向变体类型的指针987654325@.

您可以将您的A 复制到AOrB

AOrB aorb = a;

您可以定义一个包含A*B* 的变体

using AStarOrBStar = boost::variant<A*, B*>;
AStarOrBStar astarorbstar = &a;

您可以将访问者应用到 AOrB 以填充 AStarOrBStar

AStarOrBStar astarorbstar = aorb.apply_visitor([](auto & x) { return &x; });

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 2014-03-16
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多