2014-04-09 1 views
0

클래스 Test와 클래스 TestImpl이 있다고 가정 해 봅시다. 나는 Impl을 시험의 내부 클래스로 만들고 싶지 않습니다. 어떻게하면 컴파일 할 때 유형을 사용하여 Impl 유형을 가져올 수있는 일부 글로벌 키 - 값 (Type-Impl) 저장소를 만들 수 있습니까? 같은컴파일 타임에 유형의 키 - 값 쌍을 등록하는 방법은 무엇입니까?

뭔가 :

Impl<Test>::Type 

이 TestImpl 발생한다.

+0

이것은 일반적인 전 처리기 매크로로 처리 할 수있는 것처럼 보입니다. 작동하지 않는 이유가 있습니까? – Edward

답변

1

가 구현하지 않고 일반적인 템플릿을 정의, 다음을 전문 : 당신이 필요로하는 유형의 각 등등

template <typename T> struct Impl; 
template<> struct Impl<Test> { typedef TestImpl Type; }; 

와.

template<typename TAG> class interface; 
template<typename TAG> class impl; 

template<typename> struct impl_of; 

template<typename TAG> 
struct impl_of<interface<TAG> > { using type = impl<TAG>; }; 

는 그 다음 folowing 정의

: 인터페이스와 구현을 구성 할 수

1

한 편리한 방법이 그들을 연결하는 태그를 사용하는 것입니다

namespace tag { 
    struct Test; 
    struct Foo; 
    struct Bar; 
    // etc. 
} 

using Test = interface<tag::Test>; 
using Foo = interface<tag::Foo>; 
using Bar = interface<tag::Bar>; 
// etc. 

을 이제 실제 클래스 정의가 Test되지 않습니다, TestImpl 등이 아니라 전문화 된 것입니다 :

template<> 
class interface<tag::Test> { 
    // Test class definition 
}; 

template<> 
class impl<tag::Test> { 
    // TestImpl class definition 
}; 

이 경우 필요한 매핑은 impl_of에 의해 제공되며 이는 한 번만 정의됩니다.

너무 많이 들릴 수도 있지만 많은 클래스 (예 : interface, impl)와 많은 특성 (예 : impl_of)을 정의하려는 경우 강력합니다.

관련 문제