Benjamin Larsen Benjamin Larsen - 2 months ago 40
C++ Question

SFINAE C++ method check

I'm trying to wrap my head around SFINAE.
We're using it to check whether a class has a method called "Passengers".

With some online examples, we constructed the following template classes.


#include "../Engine/carriage.h"

namespace TSS{

template<typename T>
class has_passengers{
typedef char one;
typedef struct{char a[2];} two;

template<typename C> static one test( decltype(&C::Passengers) );
template<typename C> static two test(...);
static bool const value = sizeof(test<T>(0)) == sizeof(one);

template<typename T>
struct CarriageTypeCheck{
static_assert(has_passengers<T>::value, "Train initialized with illegal carriage");


#endif // TYPECHECK

I get the part how either of the two test-methods is chosen, but what I don't understand is why
is initialized with 0 in the following line:

static bool const value = sizeof(test<T>(0)) == sizeof(one);

I can not see how the 0 is important for the check to work.
Another thing - why is decltype used?


The first overloaded function (potentially) takes a pointer to a class method, as a parameter. Due to C++'s legacy from C, the value 0 is convertible to a NULL pointer, or nullptr. So, if SFINAE does not kick out the first overloaded function, test<T>(0) becomes a valid function call, and its sizeof is equal to sizeof(one). Otherwise this resolves to the second overloaded function call.

And the short answer as to why decltype is used: otherwise it would not be valid C++. In a function declaration, the function's parameter must be types, specifying the types of the parameters to the function. &C::Passengers is not a type (in the context of its intended use), so this would not be valid C++. decltype() of that automatically obtains the type of its argument, making it valid C++.