以下代码如何工作?
typedef char (&yes)[1];
typedef char (&no)[2];
template <typename B, typename D>
struct Host
{
operator B*() const;
operator D*();
};
template <typename B, typename D>
struct is_base_of
{
template <typename T>
static yes check(D*, T);
static no check(B*, int);
static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};
//Test sample
class Base {};
class Derived : private Base {};
//Expression is true.
int test[is_base_of<Base,Derived>::value && !is_base_of<Derived,Base>::value];
Run Code Online (Sandbox Code Playgroud)
请注意,这B是私人基地.这是如何运作的?
注意operator B*()是const.它为什么如此重要?
为什么template<typename T> static yes …
在/sf/answers/137702841/中,提供了一种解决方案,用于静态检查成员是否存在,可能在类型的子类中:
template <typename Type>
class has_resize_method
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void resize(int){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
Run Code Online (Sandbox Code Playgroud)
但是,它不适用于C++ 11 final类,因为它继承了被测试的类,这会final阻止它.
OTOH,这一个:
template <typename C>
struct has_reserve_method {
private:
struct No …Run Code Online (Sandbox Code Playgroud)