Why does it work? SFINAE [closed]
template<class T, class U>
struct is_convertible
{
typedef char yes;
typedef struct
{char _[2];}no;
static yes test(U);
static no test(...);
enum {value = (sizeof(test(0)) == sizeof(yes)) ? 1 : 0};
//THE PART I'M INTERESTED IN IS (test(0)). Why 0 (zero) works here?
};
Please see comment in the code.
Code "works" when it meets its specification.
This code does not meet the specification implied by the function name, and no clearer specification has been given.
Currently, the code yields is_convertible<T, U>::value
true when U
is copyable and an implicit conversion exists in the context of struct is_convertible
from int
or any pointer to U
, may not compile if U
is not copy-constructible, and false otherwise.
The assumed specification, based on a combination of the name and existing code, is that is_convertible<T, U>::value
should be true if U
is copy-constructible (in the context of struct is_convertible
) and a value of type T
is implicitly convertible (in the context of struct is_convertible
) to U
.
A slight modification is required to make the code meet the implied specification:
enum {value = (sizeof(test(*(T*)0)) == sizeof(yes)) ? 1 : 0};
精彩评论