c++实现delegate—模版函数指针

原文地址:http://www.cppblog.com/tonykee/archive/2008/09/29/63034.html

#include "stdafx.h"

#include <iostream>

using namespace std;

template<typename T>
class A
{
private:
	typedef int (T::*delegateFun)(int);
	T * _This;
	delegateFun _deleGate;

public:    

	//This被代理的对象, delegateFun被代理的方法

	A(T * This, int (T::*delegateFun)(int))
	{
		_This = This;
		_deleGate = delegateFun;
	}

	//c被代理的参数
	int execue(int c)
	{
		return (_This->*_deleGate)(c);
	}

};

class B
{
public:
	int FunA(int a) {return a + 10;}
	int FunB(int a) {return a - 10;}
	B()
	{

	}
};

int _tmain(int argc, _TCHAR* argv[])
{

	B *objB = new B();

	A<B>  delegateObj1(objB, (&B::FunA));
	A<B>  delegateObj2(objB, (&B::FunB));

	cout << delegateObj1.execue(10) <<endl;
	cout << delegateObj2.execue(20) <<endl;

	return 0;

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在CLR/C++中,可以使用委托来实现函数指针的功能委托是一种类型安全的函数指针,可以用于引用和调用函数。以下是使用CLR/C++定义和使用委托的示例: ```cpp #include <iostream> // 定义委托类型 delegate void MyDelegate(int); // 示例函数1 void Function1(int value) { std::cout << "Function1 called with value: " << value << std::endl; } // 示例函数2 void Function2(int value) { std::cout << "Function2 called with value: " << value << std::endl; } int main() { // 声明委托变量 MyDelegate^ myDelegate; // 将委托绑定到函数1 myDelegate = gcnew MyDelegate(&Function1); // 调用委托,实际上调用了函数1 myDelegate->Invoke(10); // 将委托绑定到函数2 myDelegate = gcnew MyDelegate(&Function2); // 调用委托,实际上调用了函数2 myDelegate->Invoke(20); return 0; } ``` 在这个示例中,我们首先使用`delegate`关键字定义了一个委托类型`MyDelegate`,它可以引用一个接受一个`int`参数并返回`void`的函数。 然后,我们定义了两个示例函数`Function1`和`Function2`,它们符合上述的委托类型。 在`main`函数中,我们声明了一个名为`myDelegate`的委托变量。 我们将`myDelegate`绑定到`Function1`并调用它,然后将`myDelegate`绑定到`Function2`并再次调用它。 使用委托时,可以使用`Invoke`方法来调用委托,实际上是在调用委托所绑定的函数。 请注意,CLR/C++中的委托与传统的C++函数指针有所不同。委托是一种引用类型,需要使用`gcnew`关键字进行实例化,并使用`^`符号来声明委托变量。委托还提供了更多的灵活性和功能,如多播委托和异步委托等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值