C++用模版封装一个万能函数

使用场景

有时候我们需要访问一些数据,并对数据进行一些操作,例如遍历一棵树,并对树的节点做一些操作。我们可以写一些DFS或者BFS遍历函数,并访问每一个节点做出相应动作, 如果我们有很多种操作行为,那么我们就需要写很多种这种遍历函数,聪明的你,可能已经想到,我可以将操作当做一个回调函数传入到遍历函数里面,这样就可以复用遍历代码。

对于单一的操作行为,这种方式是有效的,但是如果有很多种不同的操作行为,显然事先定义好的回调函数,可能不够用了。对于这种需求场景,我们可以使用访问者设计模式(Visit模式),该设计模式是典型的将数据和数据的操作分离的方法。不过,这里我并不想介绍访问者模式,而是介绍怎么用模版实现一个具有弹性的"回调函数",可以包装任意返回值,任意函数体,任意参数的可调用对象。

代码实现

闲话不说,直接看代码,核心是利用function和可变参数模版。

cpp 复制代码
#include <iostream>
#include <functional>

template<typename RetType>
class UniversalWrapper {
public:
	// 构造函数,接受一个函数和任意
	template<typename Func, typename... Args>
	UniversalWrapper(Func&& func, Args&&... args)
		: func_(std::bind(std::forward<Func>(func), std::forward<Args>(args)...)) {}

	// 仿函数
	RetType operator()() {
		return func_();
	}

private:
	std::function<RetType( )> func_;
};

int add(int a, int b) {
	return a + b;
}

std::string greet(const std::string& name, const std::string& greeting = "Hello") {
	return greeting + ", " + name + "!";
}

int main() {
	
	UniversalWrapper<int> wrapper1(add, 3, 5);  
	UniversalWrapper<std::string> wrapper2(greet, "Alice", "Hi"); 

	auto result1 = wrapper1();  
	auto result2 = wrapper2(); 

	std::cout << "Result1: " << result1 << std::endl; 
	std::cout << "Result2: " << result2 << std::endl; 

	return 0;
}

总结

这个实现通过模板参数 RetType 指定了返回值类型,并使用 std::function<RetType()> 存储绑定后的函数。你能够灵活地传递不同的函数和参数,并使用仿函数的形式调用它们。 这里你也可以把operator()设计成带参数的函数,只要在bind的时候留好place_holder就可以了。

相关推荐
宝贝儿好3 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
2401_884602276 小时前
程序人生-Hello’s P2P
c语言·c++
weixin_458872616 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll6 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
初中就开始混世的大魔王6 小时前
2 Fast DDS Library概述
c++·中间件·信息与通信
MediaTea6 小时前
Python:collections.Counter 常用函数及应用
开发语言·python
爱淋雨的男人6 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn7 小时前
模拟题刷题3
java·数据结构·算法