//\"저기 말이죠., 미스터 프레지던트... 그루지야놈들이 도발해서, 버르장머리 좀 고쳐주려고 우리가 침공했소. 이해해주쇼.\"




지난 번에는 상속 문제 때문에 Singleton<Foo>::GetInstance()... 꼴로 쓰자고 했잖아.

근데 관념적으로는 저게 좀 어색한 코드거든. Singleton의 인스턴스를 가져오는 모양 같아.




게다가 원래는 Foo::GetInstance()꼴로 써왔기도 하고 해서, 고민을 좀 해봤는데,

단일체 함수자 템플릿이라고는 대충 이름을 지었는데,

파생 클래스가 기초 클래스와 같은 이름의 멤버 변수를 갖고 있을 때,

기초 클래스의 것을 가려버리는 특성을 이용한 거야.

//FunctorSingleton
template <class T>
class FunctorSingleton
{
public:
        T* operator()(void)
        {
                if(mThis)
                        return mThis;
                else
                        return mThis = new T;
        }
protected:
        static T* mThis;
};
template <class T> T* FunctorSingleton<T>::mThis = 0;

//용법

class Foo
{
public:
        virtual void RetrieveSelf()
        {
                std::cout << \"Foo\" << std::endl;
        }
public:
        static FunctorSingleton<Foo> GetInstance;
};
FunctorSingleton<Foo> Foo::GetInstance;

class Bar : public Foo
{
public:
        virtual void RetrieveSelf()
        {
                std::cout << \"Bar\" << std::endl;
        }
public:
        static FunctorSingleton<Bar> GetInstance;
};
FunctorSingleton<Bar> Bar::GetInstance;

int main(void)
{
        Foo::GetInstance()->RetrieveSelf();
        Bar::GetInstance()->RetrieveSelf();
}

//결과
Foo
Bar

나름 그럴 듯한 것 같아서 한 번 올려봤음..