2008-09-10 4 views
2

필자는 필요한 기능을 구현하는 다른 클래스를 감싸는 래퍼 클래스 (일반적인 인터페이스 역할을한다) 인 클래스를 사용했다. 그래서 내 코드는 이렇게 보입니다. 이제C++에서 템플릿으로 상속 확인

template<typename ImplemenationClass> class WrapperClass { 
// the code goes here 
} 

은 어떻게

<? extends BaseClass> 

구문 자바의 제네릭과 유사한, ImplementationClass는 클래스의 집합에서 파생 될 수 있는지 확인합니까?

답변

7

는 자세한하지만 당신은 이런 식으로 작업을 수행 할 수 있습니다 :이 표준에 대한 좋은 지원하는 컴파일러 (가장 최근의 컴파일러가 잘되어야하지만, 비주얼 C의 이전 버전은 ++되지 않습니다)가 필요합니다

#include <boost/utility/enable_if.hpp> 
#include <boost/type_traits/is_base_of.hpp> 

struct base {}; 

template <typename ImplementationClass, class Enable = void> 
class WrapperClass; 

template <typename ImplementationClass> 
class WrapperClass<ImplementationClass, 
     typename boost::enable_if< 
     boost::is_base_of<base,ImplementationClass> >::type> 
{}; 

struct derived : base {}; 
struct not_derived {}; 

int main() { 
    WrapperClass<derived> x; 

    // Compile error here: 
    WrapperClass<not_derived> y; 
} 

. 자세한 내용은 Boost.Enable_If documentation을 참조하십시오.

페루 치오 말했듯이

, 간단하지만 덜 강력한 구현 :

#include <boost/static_assert.hpp> 
#include <boost/type_traits/is_base_of.hpp> 

struct base {}; 

template <typename ImplementationClass> 
class WrapperClass 
{ 
    BOOST_STATIC_ASSERT((
     boost::is_base_of<base, ImplementationClass>::value)); 
}; 
+0

enable_if 대신 BOOST_STATIC_ASSERT를 사용하면 조금 더 명확해질 수 있습니다. 즉 BOOST_STATIC_ASSERT (boost :: is_base_of ); – Ferruccio

+0

네, 제가 추가했습니다. 그것은 당신이 다른 버전을 가지고 약간 좋은 오류 메시지 (IMO)를 제공하므로 enable_if를 선호합니다. 어떤 사람들은 MPL의 정적 주장의 오류 메시지도 좋아합니다. –

+0

고마워, 저것은 일했다 :) – JSN

2

현재 상황에서는 의견이나 타사 솔루션 이외의 좋은 방법이 없습니다. Boost는 이것을 위해 concept check library을 제공하며 gcc에도 구현이 있다고 생각합니다. 개념은 C++ 0x 개선 목록에 있지만 하위 유형을 지정할 수 있는지 여부는 확실하지 않습니다. 이러한 유형은 "대략 이러한 작업을 지원해야합니다"와 비슷합니다 (대략적으로 동일).

편집 : Wikipedia는 초안 제안보다 훨씬 쉽게 읽을 수있는 C++ 0x의 개념에 대해 section을 가지고 있습니다.

0

Stoustrup's own words on the subject를 참조하십시오.

기본적으로 작은 클래스입니다. 즉, 어딘가에서 인스턴스화하는 작은 클래스입니다. 템플릿 화 된 클래스 생성자.

template<class T, class B> struct Derived_from { 
    static void constraints(T* p) { B* pb = p; } 
    Derived_from() { void(*p)(T*) = constraints; } 
}; 
관련 문제