c++ - 是否可以在元组元素上应用通用函数?

标签 c++ c++11 c++14

我发现了一个用于元组的 for_each 循环,它只是遍历元素并将它们传递给一个函数。

namespace std {
  template<int I, class Tuple, typename F> struct for_each_impl {
    static void for_each(const Tuple& t, F f) {
      for_each_impl<I - 1, Tuple, F>::for_each(t, f);
      f(get<I>(t));
    }
  };
  template<class Tuple, typename F> struct for_each_impl<0, Tuple, F> {
    static void for_each(const Tuple& t, F f) {
      f(get<0>(t));
    }
  };
  template<class Tuple, typename F>
  void for_each(const Tuple& t, F f) {
    for_each_impl<tuple_size<Tuple>::value - 1, Tuple, F>::for_each(t, f);
  }
}

.

auto t = std::make_tuple(Foo(),Bar(),Baz());
std::for_each(t,[](???){});

是否可以有这样一个通用函数?

std::for_each(t,[](T &&t){t.foo();});

最后我只想拥有适用于每个元组的东西。

std::get<0>(t).foo();
std::get<1>(t).foo();
std::get<2>(t).foo();
...

也许使用宏会更容易?

最佳答案

您可以使用通用 lambda 表达式:

for_each(t, [] (auto&& t) { std::forward<decltype(t)>(t).foo(); });

你可以声明你自己的仿函数:

struct Lambda
{
    template <typename T>
    void operator()(T&& t) const { std::forward<T>(t).foo(); }
};

for_each(t, Lambda{});

或者,如果您希望根据当前正在处理的元组元素的类型应用不同的函数,那么自定义仿函数再次成为解决之道:

struct Lambda
{
    void operator()(const Foo& foo) const { foo.foo(); }
    void operator()(const Bar& bar) const { bar.bar(); }
    void operator()(const Baz& baz) const { baz.baz(); }
};

for_each(t, Lambda{});

附带说明:不要在 std 命名空间内定义函数。

关于c++ - 是否可以在元组元素上应用通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959597/

相关文章:

c++ - "function type"表示什么

c++ - 二维数组操作的康威游戏错误

c++ - 数行和模数 C++

templates - 部分模板特化,不完整类型的无效使用

c++ - 默认值 C++11,编译器到编译器

c++ - 迭代元组......再次

c++ - 如何使用 STL 将数字格式化为有效数字

c++ - 显式模板实例化示例

c++11 - 是所有数据成员都初始化为 0 还是由自动调用的构造函数分配随机值?

c++ - 为什么所有 C++ 编译器都会因为这段代码而崩溃或挂起?