Determining whether a type is complete is a crucial aspect of programming. While the Boost library offers a wide range of TypeTraits, there is a noticeable absence of an is_complete template. This article explores why such a template is missing and proposes a solution that employs SFINAE.
The immediate challenge in defining an is_complete template lies in the fact that applying sizeof to an incomplete type is illegal. This restriction stems from the possibility of ambiguities and undefined behavior arising from the absence of a valid object size.
To work around this limitation, Alexey Malistov proposed a platform-specific solution that leverages compiler-specific macros. His approach relies on the __COUNTER__ macro, which increments with each macro invocation. This allows the construction of a template with a unique dummy parameter for each type being tested.
The code for this solution looks like this:
<code class="cpp">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</code>
By defining is_complete as a nested class template and utilizing the __COUNTER__ macro as a discriminator, it becomes possible to check for type completeness in a platform-specific manner. The pass function serves as a dummy argument for applying sizeof and differentiating between complete and incomplete types.
While the SFINAE (Substitution Failure is Not an Error) mechanism is commonly used to enable or disable template specialization based on type properties, it cannot be directly applied to check for type completeness. The reason for this is that is_complete must evaluate to a constant, not a type.
The absence of a standard is_complete template in the Boost library is due to the challenges posed by applying sizeof to incomplete types and the limitations of SFINAE. However, platform-specific solutions, such as the one proposed by Alexey Malistov, can provide a practical way to check for type completeness in certain environments.
The above is the detailed content of Why is There No Standard `is_complete` Template in Boost?. For more information, please follow other related articles on the PHP Chinese website!