Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在[modern]C++;_C++_C++11_Boost_C++14_C++17 - Fatal编程技术网

C++ 在[modern]C++;

C++ 在[modern]C++;,c++,c++11,boost,c++14,c++17,C++,C++11,Boost,C++14,C++17,通过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 {}; st

通过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;
    });
}
#包括
#包括
#包括
#包括
结构A{};
结构B{};
结构C{};
结构D{};
结构E{};
int main(){
使用名称空间std;
分别使用boost::hana::for_;
A A;
B B;
C C;
D;
E;
对于每个(连接(a、b、c、d、e),[](自动和x){
你可以使用:(C++11)()

在C++17中,使用折叠表达式,它将是:

template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    (static_cast<void>(f(std::forward<Ts>(args))), ... );
}
模板
无效应用(F、Ts和…参数){
(静态_-cast(f(std::forward(args)),…);
}
我喜欢C++11中的:

#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;
    }
}
#包括
结构S{int number;};
int main(){
s1{1};
s2{2};
s3{3};
对于(自动i:{s1,s2,s3}){

如果你有5个变量,你想用它们做同样的事情,你可能需要一个数组或向量…(或另一种类型的集合)我的问题是:为什么你想要相同的操作(实际上,它不能是相同的操作,它必须是一个模板或重载)在不同的类型上?这闻起来像是糟糕的设计。你能给出一个真实世界的例子吗?@stefan这个问题只是一个练习,答案已经提供了。@pepper_chico我看到了问题和答案。我没有看到的是它背后的问题和用例。我要发布这个:)C++11函子可能是这样的:请随意复制粘贴到您的答案中。@stefan:我的链接示例也提供了一个:),但无论如何还是要感谢。啊,我想我应该点击那个链接;-)oneliner:
(void)(const int[]){(f(std::forward(args)),0)…}
很好,但遗憾的是,它只适用于相同类型的变量。
template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    (static_cast<void>(f(std::forward<Ts>(args))), ... );
}
#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;
    }
}