相关疑难解决方法(0)

迭代不同的类型

给出以下代码:

struct Window{
    void show();
    //stuff
}w1, w2, w3;

struct Widget{
    void show();
    //stuff
}w4, w5, w6;

struct Toolbar{
    void show();
    //stuff
}t1, t2, t3;
Run Code Online (Sandbox Code Playgroud)

我想要show一堆物品:

for (auto &obj : {w3, w4, w5, t1})
    obj.show();
Run Code Online (Sandbox Code Playgroud)

然而,这不会编译,因为std::initializer_list<T>for-loop中无法推断T,事实上并没有真正T适合的.我不想创建类型擦除类型,因为需要大量的代码和不必要的运行时开销.如何正确编写循环以便obj分别为概念列表中的每个项推导出类型?

c++ c++11 c++14

62
推荐指数
6
解决办法
5886
查看次数

模板元组 - 在每个元素上调用一个函数

我的问题在于代码:

template<typename... Ts>
struct TupleOfVectors {
  std::tuple<std::vector<Ts>...> tuple;

  void do_something_to_each_vec() {
    //Question: I want to do this:
    //  "for each (N)": do_something_to_vec<N>()
    //How?
  }

  template<size_t N>
  void do_something_to_vec() {
    auto &vec = std::get<N>(tuple);
    //do something to vec
  }
};
Run Code Online (Sandbox Code Playgroud)

c++ templates tuples c++11

37
推荐指数
5
解决办法
2万
查看次数

标签 统计

c++ ×2

c++11 ×2

c++14 ×1

templates ×1

tuples ×1