본문 바로가기

3.구현/C or C++

Morden Programming의 Functor

모던 프로그래밍의 Functor이다. Functor를 우리말로 옮기면 함수자이다.

세부적인 설명은 하지 않겠다.

대충 코드를 간략하게 요약해서 함수자에 필요한 코드만 정리해다.

// defaulttype.h
#pragma once

struct NullType {};

struct EmptyType {};
// typelist.h
#pragma once

#include "defaulttype.h"

template 
struct Typelist
{
	typedef T Head;
	typedef U Tail;
};



#define TYPELIST_1(T1) Typelist
#define TYPELIST_2(T1, T2) Typelist
#define TYPELIST_3(T1, T2, T3) Typelist

// TypeAt
template  struct TypeAt;

template 
struct TypeAt, 0>
{
	typedef Head Result;
};

template 
struct TypeAt, i>
{
	typedef typename TypeAt::Result Result;
};

template 
struct TypeAtNonStrict
{
	typedef DefaultType Result;
};

template 
struct TypeAtNonStrict, 0, DefaultType>
{
	typedef Head Result;
};

template 
struct TypeAtNonStrict, i, DefaultType>
{
	typedef typename TypeAtNonStrict::Result Result;
};
// functor.h
#pragma once

#include 

#include "typelist.h"


//template 
//class Functor
//{
//public:
//	R operator() ();
//};
//
//typedef Functor myFun;

template 
class FunctorImpl;

template
class FunctorImpl
{
public:
	virtual R operator() () = 0;
	virtual FunctorImpl* clone() const = 0;
	virtual ~FunctorImpl() {}
};

template
class FunctorImpl
{
public:
	virtual R operator() (P1) = 0;
	virtual FunctorImpl* clone() const = 0;
	virtual ~FunctorImpl() {}
};

template
class FunctorImpl
{
public:
	virtual R operator() (P1, P2) = 0;
	virtual FunctorImpl* clone() const = 0;
	virtual ~FunctorImpl() {}
};

template
class Functor
{
	typedef FunctorImpl Impl;

public:
	typedef TList ParamList;
	typedef R ResultType;
	typedef typename TypeAtNonStrict::Result Param1;
	typedef typename TypeAtNonStrict::Result Param2;
	
public:
	//Functor();
	//Functor(const Functor&);
	//Functor& operator +=(const Functor&);
	//explicit Functor(std::auto_ptr spImpl);

	template 
	Functor(Fun fun);

	R operator () ()
	{
		return (*spImpl_)(); 
	}
	
	R operator () (Param1 p1)
	{
		return (*spImpl_)(p1); 
	}

	R operator () (Param1 p1, Param2 p2)
	{
		return (*spImpl_)(p1, p2);
	}

private:
	//typedef FunctorImpl Impl;
	std::auto_ptr spImpl_;
};

template
template
Functor::Functor(Fun fun) : spImpl_(new FunctorHandler(fun))
{
}

template 
class FunctorHandler : public FunctorImpl
{
public:
	typedef typename ParentFunctor::ResultType ResultType;
	
	FunctorHandler(const Fun& fun): fun_(fun) {}
	FunctorHandler* clone() const { return new FunctorHandler(*this); }

	ResultType operator () ()
	{
		return fun_(); 
	}

	ResultType operator () (typename ParentFunctor::Param1 p1)
	{
		return fun_(p1); 
	}

	ResultType operator () (typename ParentFunctor::Param1 p1, typename ParentFunctor::Param2 p2)
	{
		return fun_(p1, p2);
	}

private:
	Fun fun_;
};

 

 

 

 

반응형

'3.구현 > C or C++' 카테고리의 다른 글

C로 객체지향 흉내내기2  (0) 2009.07.27
C로 객체지향 흉내내기1  (0) 2009.07.23
전처리(preprocess) 중간 결과 확인하기  (2) 2008.09.23
STL에서 문자열 트림 (string trim)하기  (0) 2008.08.13
함수호출 규약  (0) 2007.06.18