2017-01-25 10 views
2

유형이 shared_ptr인지 여부를 찾는 데 templatized 방법을 사용하고 싶습니다.이 유형을 기반으로 함수의 새로운 특수화를 원합니다. t.value가 shared_ptr의 경우 예 주요 기능은컴파일 타임에 유형이 shared_ptr인지 감지하는 방법

,

template <class T> inline 
void CEREAL_LOAD_FUNCTION_NAME(RelaxedJSONInputArchive & ar, NameValuePair<T> & t) 
{ 
    std::cout << " CEREAL_LOAD_FUNCTION_NAME NameValuePair 1 " << std::endl; 
    ar.setNextName(t.name); 
    ar(t.value); 
} 

는 내가 다른 기능의 전문화를 갖고 싶어. 나는 아래

template <class T> inline 
typename std::enable_if<is_pointer<T>::value, void>::type 
CEREAL_LOAD_FUNCTION_NAME(RelaxedJSONInputArchive & ar, NameValuePair<T> & t) 
{ 
    std::cout << " CEREAL_LOAD_FUNCTION_NAME NameValuePair 2 " << std::endl; 
    ar.setNextName(t.name); 
    ar(t.value); 
    } 

을 시도하지만 작동하지 않습니다. 이것들은 C++ 11 시리얼 라이브러리의 일부입니다. 어느 것을 사용자 정의하려고합니다.

+0

'NameValuePair'는't.value'이 무엇을 알려주는 멤버 유형이 있습니까? – TartanLlama

+0

NameValuePair가 여기에 정의됩니다. https://uscilab.github.io/cereal/assets/doxygen/helpers_8hpp_source.html .it에는 유형 값 구성원이 있습니다. –

+0

"직접적인"과부하가 작동해야합니다. http://coliru.stacked-crooked.com/a/db3eae53e609bcfc – sp2danny

답변

6

다음은 도움이 될 수

template<typename T> struct is_shared_ptr : std::false_type {}; 
template<typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {}; 

은 당신이 올바른 기능을 얻기 위해 다음을 수행 할 수

template <class T> 
typename std::enable_if<is_shared_ptr<decltype(std::declval<T>().value)>::value, void>::type 
func(T t) 
{ 
    std::cout << "shared ptr" << std::endl; 
} 

template <class T> 
typename std::enable_if<!is_shared_ptr<decltype(std::declval<T>().value)>::value, void>::type 
func(T t) 
{ 
    std::cout << "non shared" << std::endl; 
} 

live demo

+0

제 경우에는 작동합니까? 사실 저는 value라는 멤버의 유형을 기반으로 함수의 새로운 특수화를 얻어야합니다. T :: value가 shared_ptr이면 새로운 전문화가 필요합니다. –

+0

.ini에 SFINAE를 사용하도록 답변을 업데이트했습니다. –

4

template specialization의 기본 경우입니다. 다음은 유형 T가 shared_ptr인지 여부를 판별하는 유형 특성입니다. 이미 사용하는 std::is_pointer과 동일한 방법으로 사용할 수 있습니다.

#include <memory> 
#include <type_traits> 

template<class T> 
struct is_shared_ptr : std::false_type {}; 

template<class T> 
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {}; 

데모 :

static_assert(is_shared_ptr<std::shared_ptr<int>>::value == true, ""); 
static_assert(is_shared_ptr<int>::value == false, "");