保存不同类型的函数到map

就不解释了,直接上代码:

/**
 * \file callback3.cc
 * \author Michael Egli
 * \date 08-Mar-2015
 * \copyright 2015 wisol technologie GmbH
 *
 * Overview
 * ========
 *
 * Shows how to store callbacks with different arguments in a collection.
 *
 * This is an example how `std::function` can be used to store different types
 * of callbacks in a single collection. This is often useful to be able to pass
 * parameters back to the caller.
 *
 * The idea is to store an emtpy base type in a collection. This base type is
 * then specialized for the different types of callbacks by deriving from it.
 */

#include <map>
#include <memory>
#include <functional>
#include <typeindex>
#include <iostream>

namespace {

// The base type that is stored in the collection.
struct Func_t {};
// The map that stores the callbacks.
using callbacks_t = std::map<std::type_index, std::unique_ptr<Func_t>>;
callbacks_t callbacks;

// The derived type that represents a callback.
template<typename ...A>
struct Cb_t : public Func_t {
	using cb = std::function<void(A...)>;
	cb callback;
	Cb_t(cb p_callback) : callback(p_callback) {}
};

// Wrapper function to call the callback stored at the given index with the
// passed argument.
template<typename ...A>
void call(std::type_index index, A&& ... args)
{
	using func_t = Cb_t<A...>;
	using cb_t = std::function<void(A...)>;
	const Func_t& base = *callbacks[index];
	const cb_t& fun = static_cast<const func_t&>(base).callback;
	fun(std::forward<A>(args)...);
}

} // end anonymous namespace

void foo1()
{
	std::cout << "foo1 is called.\n";
}

void foo2(int i)
{
	std::cout << "foo2 is called with: " << i << "\n";
}

void foo3(std::string s, int i)
{
	std::cout << "foo3 is called with: " << s << " and: " << i << "\n";
}

int main()
{
	// Define our functions.
	using func1 = Cb_t<>;
	std::unique_ptr<func1> f1(new func1(&foo1));
	using func2 = Cb_t<int>;
	std::unique_ptr<func2> f2(new func2(&foo2));
	using func3 = Cb_t<std::string, int>;
	std::unique_ptr<func3> f3(new func3(&foo3));

	// Add the to the map.
	std::type_index index1(typeid(f1));
	std::type_index index2(typeid(f2));
	std::type_index index3(typeid(f3));
	callbacks.insert(callbacks_t::value_type(index1, std::move(f1)));
	callbacks.insert(callbacks_t::value_type(index2, std::move(f2)));
	callbacks.insert(callbacks_t::value_type(index3, std::move(f3)));

	// Call the callbacks.
	call(index1);
	call(index2, 5);
	call(index3, std::string("an answer of"), 42);

	return 0;
}

详情请参考:

http://wisol.ch/w/articles/2015-03-08-callbacks-in-cpp11/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值