Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c++ - How to decide if a template specialization exist

I would like to check if a certain template specialization exist or not, where the general case is not defined.

Given:

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

I would like to define a struct like this:

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

Is there a way to do that (ideally without C++11)?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...