构建含有第n型中的变体类型索引的值的升压变体? [英] Construct a boost variant containing a value of the nth-type in the variant type index?

查看:162
本文介绍了构建含有第n型中的变体类型索引的值的升压变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要构建的boost ::变种取值包含缺省构造值,具有类型的索引指定的 - 不超过类型的索引写我自己的switch语句

I want to construct boost::variants containing default-constructed values, specified with a type index - without writing my own switch statement over the type index.

我想这个的必须的可能,不知何故,与MPL?

I figure this must be possible, somehow, with MPL?

要澄清,虽然,该指数的不是编译时间常数前pression。

To clarify though, the index is not a compile-time constant expression.

用例是,我需要构建稍后将包含正确的数值1替换变体,但在这一点上,我只知道类型的索引。把它看成是一个懒惰的deserialisation问题。

The use case is that I need to construct a variant which will later be replaced with one containing the correct value, but at this point I only know the type index. Think of it as a lazy deserialisation problem.

推荐答案

您需要使用变种::类型的typedef。这给你一个MPL兼容的序列,我们可以用 MPL ::在然后使用和模板,供我驱策。这是卓有成效的:

You need to use the variant::types typedef. This gives you an MPL compatible sequence which we can then use with mpl::at and a template to do our bidding. This does the trick:

#include <string>
#include <boost/variant.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>

template<typename U, typename V>
void construct_in(V& v) {
  v = U();
  // modern
  // v = U{};
}

int main()
{
  typedef boost::variant<int, std::string> variant;
  typedef boost::mpl::at<variant::types, boost::mpl::int_<1>>::type pos;
  variant v;
  // use type deduction
  construct_in<pos>(v);
  // does not throw, does work
  std::string& s =boost::get<std::string>(v);
  return 0;
}

下面去运行时变的:

#include <string>
#include <vector>
#include <functional>

#include <boost/variant.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/for_each.hpp>

typedef boost::variant<int, std::string> variant;
typedef variant::types types;
typedef std::vector< std::function<void(variant&)> > fvec;

template<typename U, typename V>
void construct_in(V& v) {
  v = U{};
}

struct build_and_add {
  fvec* funcs;
  template<typename T>
  void operator()(T) {
    funcs->push_back(&construct_in<T, variant>);
  }
};


int main()
{

  variant v;
  std::vector< std::function<void(variant&)> > funcs;

  // cannot use a lambda, would need to be polymorphic
  build_and_add f = {&funcs};
  boost::mpl::for_each<types>(f);

  // this is runtime!
  int i = 1;

  funcs[i](v);
  // does not throw, does work
  std::string& s =boost::get<std::string>(v);
  return 0;
}

这是一个有点晦涩难懂,将需要一些调整与可变参数
论点要真正通用的,但你想要做什么。别人需要弄清楚,如果这导致显著
code吹胀。

It's a little arcane and will need some tweaking with variadic arguments to be truly generic, but it does what you want. Someone else needs to figure out if this results in significant code blow-up.

这篇关于构建含有第n型中的变体类型索引的值的升压变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆