函数调用之可变参数模版

文章展示了如何使用C++模板实现可变参数的函数调用,包括通过tuple和索引序列进行解包的call函数,以及直接传递参数的call1和call2函数。call1类似于std::invoke的方式处理参数。在main函数中,这些函数被用于调用一个接受四个参数的函数f。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:

        看到了一个c++大佬的一个可变参数的函数调用,有点神奇,所以在它的基础上加了些自己的改动

代码

#include <iostream>
#include <functional>
#include <thread>
#include <format>
#include <numeric>
#include <tuple>

template<typename ...T, typename C>
void call(std::tuple<T...>&_tup, C (*f)(T...))
{
	[&] <class TupType, size_t ...I>(const TupType &_tup, std::index_sequence<I...>){
		f(std::get<I>(_tup)...);
	}(_tup, std::make_index_sequence<sizeof...(T)>());

}
template<typename C, typename ...T >
void call1(C (*f)(T...), T ...args)
{
	//std::tuple<T...> _tup = {args...};//tuple 构造方法
	//std::tuple<T...> _tup  {args...};//一致性初始化列表
	std::tuple<T...> _tup  =std::make_tuple(args...);//make_tuple构造
	[&] <class TupType, size_t ...I>(const TupType &_tup, std::index_sequence<I...>){
		f(std::get<I>(_tup)...);
	}(_tup, std::make_index_sequence<sizeof...(T)>());

}


template<typename C, typename ...T >
void call2(C (*f)(T...), T ...args)
{
        f(args...);
}
void f(int a, double b, char c, int d)
{
        std::cout<<a<<b<<c<<d<<std::endl;
}
int main()
{
        std::tuple<int,double, char,int> t(1, 1.2, '*', 10);
        call(t, f);
        call1(f, 1,1.2,'*',10);
        call2(f, 1,1.2,'*',10);
        std::invoke(f, 1,1.2,'*',10);


分析:

        call1 是我参照上边的写的,主要把tuple拆成了可变参数,这样调用的时候,传递函数指针与对应的参数,跟std::invoke 比较类似. call2就更简单了,直接调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值