我发现了一个用于元组的 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();
...
也许使用宏会更容易?
最佳答案
在c++14您可以使用通用 lambda 表达式:
for_each(t, [] (auto&& t) { std::forward<decltype(t)>(t).foo(); });
在c++11你可以声明你自己的仿函数:
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/