Search code examples
c++templatestype-traitsc++03

How to write `is_complete` template?


After answering this question I was trying to find is_complete template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like?

//! Check whether type complete
template<typename T>
struct is_complete
{   
  static const bool value = ( sizeof(T) > 0 );
};

...

// so I could use it in such a way
BOOST_STATIC_ASSERT( boost::is_complete<T>::value );

The code above is not correct, because it is illegal to apply sizeof to an incomplete type. What will be a good solution? Is it possible to apply SFINAE in this case somehow?


Well, this problem couldn't be solved in general without violating the ODR rule, but there is there a platform specific solution which works for me.


Solution

  • The answer given by Alexey Malistov can be used on MSVC with a minor modification:

    namespace 
    {
        template<class T, int discriminator>
        struct is_complete {  
          static T & getT();   
          static char (& pass(T))[2]; 
          static char pass(...);   
          static const bool value = sizeof(pass(getT()))==2;
        };
    }
    #define IS_COMPLETE(X) is_complete<X,__COUNTER__>::value
    

    Unfortunately, the __COUNTER__ predefined macro is not part of the standard, so it would not work on every compiler.