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?
};
Run Code Online (Sandbox Code Playgroud)
请在代码中查看评论.
代码符合其规范时"有效".
此代码不符合函数名称隐含的规范,并且未给出更清晰的规范.
目前,代码is_convertible<T, U>::value在U可复制时产生true,并且在struct is_convertiblefrom int或任何指针的上下文中存在隐式转换U,如果U不是可复制构造的则可能无法编译,否则可能为false.
假定的规范,基于名称和现有代码的组合,is_convertible<T, U>::value如果U是可复制构造的(在上下文中struct is_convertible)并且type的值T可以隐式转换(在上下文中struct is_convertible),则应该为true U.
需要稍作修改才能使代码符合隐含的规范:
enum {value = (sizeof(test(*(T*)0)) == sizeof(yes)) ? 1 : 0};
Run Code Online (Sandbox Code Playgroud)