http://blog.naver.com/waraccc/116732322
boost::function 은 일종의 함수포인터처럼 사용이 가능합니다.( function wrapper )
과거에 사용했었던 함수 포인터를 대처해서 사용이 가능하죠 뿐만 아니라 ( 함수 + 추가 정보 )를 패키지로 저장해서
들고 다기는것도 가능합니다.( 라고는 얘기 하는데 솔직히 무슨 소리인지는 모르겠네요 -ㅅ- )
예제를 쌈빡하게 보도록 하죠...
함수포인터를 사용해서 해외 코드 관리를 할수 있는 간략한 예제를 한번 boost::function을 사용하여
변경한 예제를 보여드리겠습니다.
#include <boost/function.hpp>
#include <iostream>
using namespace std;
class DoSomething_CN
{
public:
void operator()()
{
cout<<"Dosomething_CN"<<endl;
}
};
class DoSomething_KR
{
public:
void operator()()
{
cout<<"DoSomething_KR"<<endl;
}
};
class DoSomething_US
{
public:
void operator()()
{
cout<<"DoSomething_US"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
boost::function<void()> selectfunc;
int nLangCode = 0;
cout<<"숫자를 입력하세요"<<endl;
cin>>nLangCode;
switch ( nLangCode )
{
case 0:
selectfunc = DoSomething_CN();
selectfunc();
break;
case 1:
selectfunc = DoSomething_KR();
selectfunc();
break;
case 2:
selectfunc = DoSomething_US();
selectfunc();
break;
}
system("PAUSE");
return 0;
}
이렇게 사용하면 함수 포인터를 대신하여 사용할 수 있습니다.
갑자기 이 예제를 보니 불과 한달전인가요? 어이없는 C모사에서 PD가 지뿔 아는것도 없으면서
함수 포인터를 절대로 사용하지 말라면서( 해외 코드 관리 부분이였죠 그때도 ) 클래스로 만들어 달라는게
생각나는군요 ㅋㅋㅋ 머 이런식으로 사용도 가능하고
클래스 안에 클래스 맴버 함수도 접근이 가능합니다.
어떤식으로 가능하냐면
class CTest
{
public:
void print( int n )
{
std::cout << "클래스 함수 입력값: " << n << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest ctest;
boost::function< void( CTest*, int ) > classfunc; //boost::function< void( CTest*, int x ) > classfunc;로 변경가능
classfunc = &CTest::print;
classfunc( &ctest, 10 );
boost::function< void(int) > classfunc2; //boost::function< void(int x) > classfunc2;로 변경가능
classfunc2 = std::bind1st( std::mem_fun( &CTest::print), &ctest );
classfunc2( 17 );
system("PAUSE");
return 0;
}
이런식으록 가능합니다. 머 주석처리 방식으로 다른 호출 방법을 적었는데
이건 머 좀 더 명확하게 해주는 방식인지라 타이핑 하기 귀춘하시면 생략하셔도 됩니다.
이상 boost::function 사용법을 간략하게 알아보았습니다. 추후에 ( 함수 + 추가 정보 )를 패키지로 저장해서
들고 다기는것도 가능하다라는 방식도 조사해서 기재해보도록하죠 -ㅅ-;
'메타프로그래밍 > Boost::' 카테고리의 다른 글
boost::weak_ptr (0) | 2012.11.24 |
---|---|
boost::shared_ptr (0) | 2012.11.18 |
boost::unordered_set (0) | 2012.11.13 |
Boost::[bind, mem_fn ] 과 STL , 멤버함수 조합사용 (0) | 2012.11.13 |
boost::bind (0) | 2012.11.13 |