c++17std::apply与std::make_from_tuple.

        在C++17标准之前,处理元组和可变参数模板是一件相对繁琐的事情。例如,如果我们想要将一个元组的所有元素作为参数传递给一个函数,我们需要手动解包元组,这通常需要使用模板元编程和递归。通过引入std::apply,我们可以轻松地将一个元组的所有元素作为参数传递给一个函数,而无需手动解包元组。这极大地提高了代码的可读性和效率。

         std::apply,std::make_from_tuple是关于std::tuple(或std::pairstd::array等可以通过std::get来操作成员的元组容器)与函数参数转化的问题的。

  •         std::apply最主要的作用就是把tuple转化为函数参数,然后去调用函数
  •   std::make_from_tuple可以直接用它来代替自行实现的Create函数

apply

template< class F, class Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t);

以参数的元组调用可调用 (Callable) 对象 f 。

f-要调用的可调用 (Callable) 对象,可以是函数、函数指针、成员函数指针、成员对象指针或者具有operator()的对象
t-以其元素为 f 的参数的元组,元组不必是 std::tuple ,可以为任何支持 std::get 和 std::tuple_size 的类型所替代;特别是可以用 std::array 和 std::pair 。

示例:

#include <iostream>
#include <tuple>
#include <functional>

void add(int a, int b) {
    std::cout << "sum = " << a + b << std::endl;
}

int main() {
    //
    std::tuply<int,int> tu = {1,2};
    std::cout << std::apply(auto x, auto y)  { return x+y; }, tu);

    std::tuple<int, int,int, int >t = {1, 2,3,4};
    std::cout << std::apply([](auto && ...args){ return (args + ...); },
        t)) << '\n';

    std::tuple<int,double,string> tup = std::make_tuple(1, 2.1, "1.2.3");
    std::apply([](auto &&... args) {
        ((std::cout << args << '\n'), ...);
    }, tup);
   
    return 0;
}

make_from_tuple

template< class T, class Tuple >
constexpr T make_from_tuple( Tuple&& t );

(since C++17)
(until C++23)

template< class T, tuple-like Tuple >
constexpr T make_from_tuple( Tuple&& t );

((since C++23)

Tuple不需要是 std::tuple,而是支持 std::get 和 std::tuple_size;特别是,可以使用 std::array 和 std::p air

(直到 C++23)

Tuple被限制为类元组,即其中的每个类型都需要是 std::tuple 或其他类型(例如 std::array 和 std::p air)的专用化,该类型建模为类元组


using namespace std;
class Object{
private:
    int num;
    string id;
public:
    Object(){}
    Object(int n, const string s) : num(n), id(s){    cout << "N,S" <<endl ;}
    void func(){
        cout << num << " - "<< id << endl;
    }
};

int main(){
    std::tuple t = {1, "hua"};
    Object && a = make_from_tuple<Object>(move(t));
    t.func();
    return 0;
}

参考:https://blog.csdn.net/fl2011sx/article/details/119217893

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值