Library2010. 11. 8. 11:59

mem_fn 의 함수 템플릿은 함수 포인트를 호출할수 있도록 포장한다.
result_of 함수 템플릿을 사용하다면 보면 리턴값의 정의가 애매모호해 지는 경우 사용한다.


#include "stdio.h"

#include 

using std::tr1::mem_fn;
using std::tr1::result_of;

class func_class
{
public:
	void print() const
	{
		printf("Hello world!!!\n");
	}
	void print_arg(char* string)
	{
		printf("%s\n", string);
	}
	int printf_return()
	{
		return 1;
	}

public:
	int mem_;
};

template 
func_print(FN fn, OB ob)
{
	//result_of 은 코딩시 리턴 형식을 정의 할수 없는 애매한 상황에 사용된다.
	typedef typename result_of::type ret;

	ret ret_val = fn(ob);

	printf("Return type of %s when called with %s is %s(%d)\n",
		   typeid(FN).name(), 
		   typeid(OB).name(), 
		   typeid(ret).name(),
		   ret_val);
	
}

void main(void)
{
	typedef void(func_class::*FUN_PRINTF)() const;
	FUN_PRINTF fn = &func_class::print;

	func_class fc;
	// 인자 없는 함수
	mem_fn(fn)(fc);					

	//인자 있는 함수
	mem_fn(&func_class::print_arg)(fc, "Hello world!!!");

	//반환 있는 함수
	func_print(mem_fn(&func_class::printf_return), fc);

	//멤버 변수 사용
	mem_fn(&func_class::mem_)(fc) = 3;
	printf("%d\n", fc.mem_);

}

Posted by 상현달