2017-05-28 38 views
9

Belirli bir şablon uzmanlığının var olup olmadığını ve genel durumun tanımlanmadığını kontrol etmek istiyorum.Şablon uzmanlaşmasının mevcut olup olmadığına nasıl karar verilir?

Verilen:

template <typename T> struct A; // general definition not defined 
template <> struct A<int> {}; // specialization defined for int 

Böyle bir yapı tanımlamak istiyorum:

template <typename T> 
struct IsDefined 
{ 
    static const bool value = ???; // true if A<T> exist, false if it does not 
}; 

(ideal olarak 11 C++ olmadan) bunu yapmak için bir yolu var mı?

Teşekkür

+1

olduğunu çalışmıyor Neden bunu yapmak gerekir? Meraktan vazgeçme. – HSchmale

+0

@HSchmale, Tam sorun burada açıklanmıştır: https://stackoverflow.com/questions/44237528/how-to-write-template-overload-functions-with-fallback-triggered-if-template-arg – Fabio

cevap

11

tamamlanmamış bir türe sizeof uygulayamazsınız gerçeğini kullanarak:

template <class T, std::size_t = sizeof(T)> 
std::true_type is_complete_impl(T *); 

std::false_type is_complete_impl(...); 

template <class T> 
using is_complete = decltype(is_complete_impl(std::declval<T*>())); 

See it live on Coliru

İşte

biraz aksak, ama çalışma C++ 03 çözüm:

template <class T> 
char is_complete_impl(char (*)[sizeof(T)]); 

template <class> 
char (&is_complete_impl(...))[2]; 

template <class T> 
struct is_complete { 
    enum { value = sizeof(is_complete_impl<T>(0)) == sizeof(char) }; 
}; 

See it live on Coliru

+0

Teşekkürler. C++ 11 olmadan bunu yapmanın bir yolu var mı? – Fabio

+0

@Fabio işte gidiyorsun. – Quentin

+0

Teşekkürler! C++ 03 çözümünde gerekli olan is_complete_impl dosyasının ikinci tanımında şablon mu var? – Fabio

0

Bu her zaman @Quentin


C++ 11 versiyonu

template<class First, std::size_t> 
using first_t = First; 

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

template<class T> 
struct is_complete_type<first_t<T, sizeof(T)>> : std::true_type {}; 

Example on wandbox


Geçici C + kullanılan aynı numara kullanan alternatif bir uygulama +03 sürümü WHI ch bu durumda

template<typename First, std::size_t> 
struct first { typedef First type; }; 

template<typename T> 
struct is_complete_type { static const bool value = false; }; 

template<typename T> 
struct is_complete_type< typename first<T, sizeof(T)>::type > { static const bool value = true; }; 

hata

prog.cc:11:8: error: template parameters not deducible in partial specialization: struct is_complete_type< typename first::type > { static const bool value = true; }; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

prog.cc:11:8: note: 'T'