遍历 N 个变量(每个变量的任何类型)以执行操作的简洁方法是什么?
假设我有变量a
, b
, c
, d
,e
并希望通过所有这些变量执行一些操作。
使用 Boost.Hana 和通用 lambda:
#include <tuple>
#include <iostream>
#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>
struct A {};
struct B {};
struct C {};
struct D {};
struct E {};
int main() {
using namespace std;
using boost::hana::for_each;
A a;
B b;
C c;
D d;
E e;
for_each(tie(a, b, c, d, e), [](auto &x) {
cout << typeid(x).name() << endl;
});
}
您可以使用:(C++11)(https://ideone.com/DDY4Si)
template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
const int dummy[] = { (f(std::forward<Ts>(args)), 0)... };
static_cast<void>(dummy); // avoid warning about unused variable.
}
使用F
仿函数(或通用 lambda (C++14))。你可以在 C++14 中这样称呼它:
apply([](const auto &x) { std::cout << typeid(x).name() << std::endl;}, a, b, c, d, e);
在 C++17 中,使用折叠表达式,它将是:
template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
(static_cast<void>(f(std::forward<Ts>(args))), ... );
}
我喜欢C++11 中基于范围的 for 循环:
#include <iostream>
struct S {int number;};
int main() {
S s1{1};
S s2{2};
S s3{3};
for (auto i : {s1, s2, s3}) {
std::cout << i.number << std::endl;
}
}