0
点赞
收藏
分享

微信扫一扫

实现一个std::function

8052cf60ff5c 2022-02-06 阅读 86
#include <iostream>
#include <string>
#include <future>
using namespace std;

//先声明一个类模板,实现类似std::function的功能
template<class T, class ...args>
class myfunction;
//特化版本
template<class T, class ...args>
class myfunction<T(args...)>
{
public:
};

void callback(myfunction<void(int, int)> obj)
{
}
void myfunc(int a,int b) //普通函数
{
	std::cout << "myfunc执行了:a = " << a << " b = " << b << std::endl;
}
int main()
{
	callback(myfunc);
    return 0;
}

此时编译报错:
在这里插入图片描述
我们改造一下这个类模板,增加一个模板构造函数

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;

//先声明一个类模板,实现类似std::function的功能
template<class T, class ...args>
class myfunction;
template<class T, class ...args>
class myfunction<T(args...)>
{
public:
	template<class U>
	myfunction(U&& i) //相当于万能引用,同时也是一个类型转换构造函数,把i转为myfunction类类型
	{
		//U是一个可调用对象类型
	}
};

void callback(myfunction<void(int, int)> obj)
{
}
void myfunc(int a,int b) //普通函数
{
	std::cout << "myfunc执行了:a = " << a << " b = " << b << std::endl;
}

int main()
{
	callback(myfunc);
    return 0;
}

此时编译通过。

我们继续。

void callback(myfunction<void(int, int)> obj)
{
  obj(1, 2);
}

这个调用以后,代码还是报错。

我们接着改类模板。

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;


//先声明一个类模板,实现类似std::function的功能
template<class T, class ...args>
class myfunction;

template<class T, class ...args>
class myfunction<T(args...)>
{
public:
	template<class U>
	myfunction(U&& i) //相当于万能引用,同时也是一个类型转换构造函数,把i转为myfunction类类型
	{
		//U是一个可调用对象类型
	}
	T operator()(args ...a)
	{
		//...
	}
};

void callback(myfunction<void(int, int)> obj)
{
	obj(1, 2);
}

void myfunc(int a,int b) //普通函数
{
	std::cout << "myfunc执行了:a = " << a << " b = " << b << std::endl;
}
int main()
{
	callback(myfunc);
    return 0;
}

此时,代码顺利编译通过。

最重要的是实现调用功能,上面最初步的代码已经完成了,接下来我们考虑在构造函数里面和运算符重载函数里面做文章,最终实现调用的目的。

todo:

举报

相关推荐

0 条评论