How to check whether operator== exists?

C++03 The following trick works and it can be used for all such operators: namespace CHECK { class No { bool b[2]; }; template<typename T, typename Arg> No operator== (const T&, const Arg&); bool Check (…); No& Check (const No&); template <typename T, typename Arg = T> struct EqualExists { enum { value = (sizeof(Check(*(T*)(0) … Read more

What exactly is the “immediate context” mentioned in the C++11 Standard for which SFINAE applies?

If you consider all the templates and implicitly-defined functions that are needed to determine the result of the template argument substitution, and imagine they are generated first, before substitution starts, then any errors occurring in that first step are not in the immediate context, and result in hard errors. If all those instantiations and implicitly-definitions … Read more

Why do constant expressions have an exclusion for undefined behavior?

The wording is actually the subject of defect report #1313 which says: The requirements for constant expressions do not currently, but should, exclude expressions that have undefined behavior, such as pointer arithmetic when the pointers do not point to elements of the same array. The resolution being the current wording we have now, so this … Read more

How to detect whether there is a specific member variable in class?

Here is a solution simpler than Johannes Schaub – litb‘s one. It requires C++11. #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 { }; Update: A quick example and the explanation on how this works. For these types: … Read more

How does `void_t` work

1. Primary Class Template When you write has_member<A>::value, the compiler looks up the name has_member and finds the primary class template, that is, this declaration: template< class , class = void > struct has_member; (In the OP, that’s written as a definition.) The template argument list <A> is compared to the template parameter list of … Read more

Check if a class has a member function of a given signature

Here’s a possible implementation relying on C++11 features. It correctly detects the function even if it’s inherited (unlike the solution in the accepted answer, as Mike Kinghan observes in his answer). The function this snippet tests for is called serialize: #include <type_traits> // Primary template with a static assertion // for a meaningful error message … Read more