Checking Existence of Class Member Variables in C
The question seeks a way to determine the presence of specific member variables, namely "x" or "X," within a class that serves as a template argument. This technique is particularly useful when working with classes like MFC CPoint or GDI PointF, each of which employs a distinct "x" member.
Proposed Solutions
The response proposes two solutions:
1. Macros-Based Solution:
This approach relies on using Visual Studio's preprocessor macros:
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; } template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
However, this solution is limited to Visual Studio and does not compile in GNU C .
2. C 11-Based Solution:
This solution leverages C 11's type traits:
#include <type_traits> template <typename T, typename = int> struct HasX : std::false_type { }; template <typename T> struct HasX <T, decltype((void) T::x, 0)> : std::true_type { };
This technique works by using SFINAE (Substitution Failure Is Not An Error) to check for member variables. If a member variable exists, the template specialization for the corresponding type will be invoked, resulting in a true return value. Otherwise, the default template will be selected, yielding a false return value.
The above is the detailed content of How Can I Check for the Existence of Member Variables 'x' or 'X' in a C Template Class?. For more information, please follow other related articles on the PHP Chinese website!