Black Moses Black Moses - 2 months ago 9
C++ Question

Check if type is defined

Consider this example:

#include <iostream>
#include <type_traits>

template <class, class = void>
struct is_defined : std::false_type
{ };

template <class T>
struct is_defined<T,
std::enable_if_t<std::is_object<T>::value &&
!std::is_pointer<T>::value
>
> : std::true_type
{
private:
static const T test; //try to create incomplete type member
};

struct defined { };

struct forward_declared;

int main()
{
std::cout << std::boolalpha
<< is_defined<defined>::value << std::endl
<< is_defined<forward_declared>::value << std::endl;
}


Output is
true
for both. I thought if I try to make
struct
member of incomplete type, then this template specialization would be discarded from overload set. But it isn't. Removal of
static const
causes incomplete-type compile-time error. What is wrong with this approach, and if it's possible, how could this be implemented?

Answer

Try this:

template <class T>
struct is_defined<T,
    std::enable_if_t<std::is_object<T>::value &&
                    !std::is_pointer<T>::value &&
                    (sizeof(T) > 0)
        >
    > : std::true_type
{
};