向量元组和推回

时间:2017-01-29 20:21:32

标签: c++ c++11 templates c++14

我有一个向量元组,我想var workerTask = restService.GetRequestAsync(articleAdr, articleParams); var cancellationTask = Task.Delay(1000, cts.Token); await Task.WhenAny(workerTask, cancellationTask); if (workerTask.Status == TaskStatus.RanToCompletion) { // Note that this is NOT a blocking call because the Task ran to completion. var response = workerTask.Result; // Do whatever work with the completed result. } else { // Handle the cancellation. // NOTE: You do NOT want to call workerTask.Result here. It will be a blocking call and will block until // your previous method completes, especially since you aren't passing the CancellationToken. } 从初始化列表中的每个值到“向量元组”中的相应向量。代码中的push_back()函数是我想要这样做的地方。

create()

示例:

template<typename...Fields>
class ComponentManager
{
  using Index = int;
public:
  /**
   * Provides a handle to a component
   **/
  struct ComponentHandle {
    static constexpr Index Nil = -1;
    bool nil() { return index == Nil; }
    const Index index;
  };

  ComponentHandle lookup(Entity e) { 
    return ComponentHandle{get(m_map,e,-1)}; 
  }

  template<int i>
  auto get(ComponentHandle handle) {
    return std::get<i>(m_field)[handle.index];
  }

  ComponentHandle create(Entity e, Fields ...fields) {
    m_entity.push_back(e);
    // m_fields.push_back ... ???
  }

private:
  std::vector<Entity>                m_entity;
  std::tuple<std::vector<Fields>...> m_field;
  std::map<Entity,Index>             m_map;
};

3 个答案:

答案 0 :(得分:3)

这可能不是很明显,但在C ++中解包元组的方法是使用std::apply()。使用C ++ 17,这很简单:

void create(Entity e, Fields ...fields) {
    m_entity.push_back(e);
    std::apply([&](auto&... vs) {
       (vs.push_back(fields), ...);
    }, m_field);
}

使用C ++ 14,我建议你自己实现apply()(它是short function),然后你需要使用expander trick而不是使用fold-expressions:

void create(Entity e, Fields ...fields) {
    m_entity.push_back(e);
    not_std::apply([&](auto&... vs) {
       using swallow = int[];
       (void)swallow{0, 
           (vs.push_back(fields), 0)...
           };
    }, m_field);
}

使用C ++ 11时,大多数情况都适用,除了我们不能使用泛型lambdas并且实现std::apply比链接引用更冗长(但不是更复杂)。值得庆幸的是,除了使代码更短之外,我们实际上并不需要其他任何东西 - 我们知道所有的矢量类型:

void create(Entity e, Fields ...fields) {
    m_entity.push_back(e);
    not_std::apply([&](std::vector<Fields>&... vs) {
       using swallow = int[];
       (void)swallow{0, 
           (vs.push_back(fields), 0)...
           };
    }, m_field);
}

答案 1 :(得分:2)

template <class F, class... Args>
void for_each_argument(F f, Args&&... args) {
    (void) std::initializer_list<int>{(f(std::forward<Args>(args)), 0)...};
}

ComponentHandle create(Entity e, Fields ...fields) 
{
    for_each_argument([&](auto field)
                  { 
                      using field_type = std::vector<std::decay_t<decltype(field)>>;
                      std::get<field_type>(m_field).push_back(field); 
                  },
                  fields...);
}

wandbox example

  

我在问题中没有提到要求字段可以是相同类型,因此例如元组中可以有几个向量。

template <typename TVec, typename TFieldTuple, std::size_t... TIdxs>
void expander(TVec& vec, TFieldTuple ft, std::index_sequence<TIdxs...>)
{
    for_each_argument([&](auto idx)
    {
        std::get<idx>(vec).push_back(std::get<idx>(ft));
    }, std::integral_constant<std::size_t, TIdxs>{}...);
}

const auto create = [](auto& vec, auto ...fields) 
{
    expander(vec, 
             std::make_tuple(fields...), 
             std::make_index_sequence<sizeof...(fields)>());
};

wandbox example

答案 2 :(得分:1)

C ++ 14解决方案,从C ++ 17实现apply一半。

template<std::size_t I>
using index_t = std::integral_constant<std::size_t, I>;
template<std::size_t I>
constexpr index_t<I> index{};

template<class=void,std::size_t...Is>
auto index_over( std::index_sequence<Is...> ) {
  return [](auto&&f)->decltype(auto) {
    return decltype(f)(f)( index<Is>... );
  };
}
template<std::size_t N>
auto index_over( index_t<N> ={} ) {
  return index_over( std::make_index_sequence<N>{} );
}


template<class F>
auto for_each_arg( F&& f ) {
  return [f = std::forward<F>(f)](auto&&...args)->decltype(auto) {
    using discard=int[];
    (void)discard{0,(void(
      f(decltype(args)(args))
    ),0)...};
  };
}

这些很有用,但不是必需的:

template<class F, class Tuple>
decltype(auto) apply( F&& f, Tuple&& tuple ) {
  auto count = index< std::tuple_size< std::decay_t<Tuple> >{} >;
  return index_over( count )( [&](auto...Is) {
    using std::get;
    return std::forward<F>(f)( get<decltype(Is)::value>( std::forward<Tuple>(tuple) )... );
  } );
}
template<class Tuple>
auto for_each_tuple_element(Tuple&& tuple) {
  return [&](auto&& f)->decltype(auto){
    return apply(
      for_each_arg( decltype(f)(f) ),
      std::forward<Tuple>(tuple)
    );
  };
}

测试代码:

int main() {
    std::tuple< std::vector<int>, std::vector<char> > tup;
    for_each_tuple_element( tup )( [](auto&& v) {
      v.push_back(3);
    });
    std::cout << std::get<0>(tup).size() << "," << std::get<1>(tup).size() << "\n";
}

live example

然后我们可以将它应用到您的问题中。

ComponentHandle create(Entity e, Fields ...fields) {
  m_entity.push_back(e);
  auto indexer = index_over<sizeof...(fields>();
  auto fields_tuple = std::forward_as_tuple( std::forward<Fields>(fields)... );
  indexer( for_each_arg([&](auto Is){
    std::get<Is>(m_fields).push_back(
      std::get<Is>(decltype(fields_tuple)(fields_tuple))
    );
  } );
}

index_over需要一个编译时N并返回一个lambda。这个lambda可以调用,并使用index_t<0>通过index_t<N-1>调用它。

for_each_arg采用可调用的方法,并返回一个带有任意数量参数的lambda。它依次调用每个参数的callable。

我们将Fields...fields拼接在一起,构建一个index_over来为我们提供编译时的索引集。然后,我们将这些字段存储在tuple r和l值引用中。

我们在单个索引Is上编写一个操作。然后我们将它传递给for_each_arg,并将返回值传递给index_over,并获得为每个索引调用的单个索引处理lambda。

某些编译器不允许非constexpr std::integral_constant转换为constexpr上下文中的标量。它们是错误的和/或过时的。对于那些人,你必须做decltype(Is)::value

相关问题