2011-05-13 3 views
11

유형이 템플릿 클래스에서 파생되었는지를 어떻게 확인할 수 있습니까? 특히 템플릿 매개 변수의 기본 클래스가 std::basic_ostream인지 확인해야합니다. 일반적으로 std::is_base_of은 작업을위한 도구입니다. 그러나 std::is_base_of은 클래스 템플릿이 아닌 완전한 유형에서만 작동합니다.형식이 템플릿 클래스에서 파생되었는지 확인하는 방법?

나는 이것을 (를) 다음과 같이 찾고 있습니다.

template< typename T > 
bool is_based_in_basic_ostream(T&& t) 
{ 
    if(std::is_base_of< std::basic_ostream< /*anything*/>, T >::value) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

나는 어떻게 생각할 수 없다고 확신합니다.

+1

그냥 던져 넣고 싶다면 ... if 문에서 조건을 반환하는 하나의'return' 라인으로 if/else 브랜치 전체를 바꿀 수 있습니다! – AshleysBrain

+0

은 완전한 형태의'typename T '입니까? 당신은 당신의 코드에서'/ * anything * /'으로 무엇을 지정할 것입니까? – iammilind

+0

필자의 경우 필자는 정수형 문자 만 볼 것으로 기대하고 있습니다. 나는 basic_ostream이'/ * anything * /'가 완전한 타입이 아니면 인스턴스화 될 수 없다고 생각한다. –

답변

12

간결하고 간결한 방법을 알지 못합니다. 하지만 다시 오버로드를 남용 할 수 있습니다.

template< typename T, typename U > 
std::true_type is_based_impl(std::basic_ostream<T, U> const volatile&); 
std::false_type is_based_impl(...); 

template< typename T > 
bool is_based_in_basic_ostream(T&& t) { 
    return decltype(is_based_impl(t))::value; 
} 

오직 공개 상속 만 탐지합니다. (이 제한된 적용의, 그래서이 테스트는 입력 스트림에 대한 긍정적 인 것) 대신

std::is_base_of<std::ios_base, T> 
+1

'std :: ios_base '를 검사 할 때의 문제점은 입력 스트림을 감지하여 OP가 원하는 의미를 위반할 수 있다는 것입니다. – ildjarn

+0

@ildjarn 동의합니다. 나는 내가 더 분명해야한다고 생각한다. 명시 적으로 지적 주셔서 감사합니다. 고정 :) –

5

부스트의 is_instance_of 같은 것이 될 수있다 동일하게 당신을 위해 작동 할 수있는, ios_base에서 유도를 감지 할 수 있습니다 무엇을 후입니까? 당신이 생산됩니다 현재 GCC (4.6.0)으로, 가변 인자 템플릿이 확장하려고하면 불행하게도

#include <iostream> 
#include <type_traits> 

template <template <typename> class F> 
struct conversion_tester 
{ 
     template <typename T> 
     conversion_tester (const F<T> &); 
}; 

template <class From, template <typename> class To> 
struct is_instance_of 
{ 
     static const bool value = std::is_convertible<From,conversion_tester<To>>::value; 
}; 

template <typename T> 
struct foo {}; 

template <typename T> 
struct bar {}; 

int main() 
{ 
     std::cout << is_instance_of<foo<int>,foo>::value << '\n'; // This will print '1'. 
     std::cout << is_instance_of<bar<int>,foo>::value << '\n'; // This will print '0'. 
} 

: 여기

http://www.boost.org/doc/libs/1_46_1/boost/lambda/detail/is_instance_of.hpp

1 인수 템플릿의 짧은 버전입니다 오류 메시지. This SO answer은 이것이 현재 GCC의 문제이며 가변 표준 템플릿 버전이 표준에 따라 작동한다고 가정합니다.

관련 문제