【问题标题】:Constructing a union tuple in C++11在 C++11 中构造联合元组
【发布时间】:2013-12-06 10:19:39
【问题描述】:

元组有点像like structs。是否还有表现得像联合的元组?或者我可以访问元组中成员的联合,例如

my_union_tuple<int, char> u;
get<1>(u);
get<int>(u); // C++14 only, or see below

关于第 2 行,请参阅 here

当然,该解决方案不仅适用于特定的联合,例如&lt;int, char&gt;,还适用于任意类型和类型数量。

【问题讨论】:

  • 这些被称为变体。 Boost 有一个实现。

标签: c++ c++11 tuples unions


【解决方案1】:

std::tuple&lt;A, B&gt; 表示 A 和 B。 如果你想要一个类型安全的类联合容器,请查看boost variant

boost::variant<int, std::string> v;

v = "hello";
std::cout << v << std::endl;

它确实为访客提供了安全的穿越:

class times_two_visitor
    : public boost::static_visitor<>
{
public:

    void operator()(int & i) const
    {
        i *= 2;
    }

    void operator()(std::string & str) const
    {
        str += str;
    }

};

如果类型不好,甚至可以抛出直接访问器:

std::string& str = boost::get<std::string>(v);

(代码取自boost variant basic tutorial

【讨论】:

  • 谢谢,听起来不错。通过查看标题,我猜 boost 不使用可变参数列表,而是使用类型列表? (C++03 等价物)
  • @Johannes 我不知道。 Boost 机制在很大程度上依赖于编译器,因为它们确实支持非常旧的编译器,所以肯定不止一种实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2018-01-23
相关资源
最近更新 更多