How to decide if a template specialization exist

*爱你&永不变心* 提交于 2019-11-27 22:56:25

Using the fact that you can't apply sizeof to an incomplete type:

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


Here is a slightly clunky, but working C++03 solution:

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

This is an alternative implementation always using the same trick @Quentin used


C++11 version

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


Tentative C++03 version which does not work

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; };

The error in this case is

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'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!