c++ - 在 [现代] C++ 中通过 N 个变量进行范围/循环

标签 c++ c++11 boost c++14 c++17

什么是遍历 N 个变量(每个变量都是任意类型)以执行操作的简洁方法?

假设我有变量abcde 并希望通过所有这些执行一些操作。

最佳答案

使用 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;
    });
}

http://coliru.stacked-crooked.com/a/ccb37ec1e453c9b4

关于c++ - 在 [现代] C++ 中通过 N 个变量进行范围/循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23235804/

相关文章:

c++ - 在 std::map 中使用 decltype

c++ - boost::serialization 存档版本介于 v1.59 和 v1.60 之间

c++ - 使用 Boost::Asio 通过 TCP 读取二进制数据

c++ - 使用 OpenGL 风扇而不是根据不同的位置创建圆有什么好处?

c++ - 使以下记录器实现线程安全的更好方法?

c++ - 在运行时调用处理 constexpr。 C++

C++ mmap到 "fast"读取与gzip文件的耦合

c++ - 减少 Tesseract OCR 执行时间

c++ - 链接列表程序在收到用户的值后崩溃

c++ - 在 C++ 中测量耗时