【发布时间】:2011-02-24 01:20:01
【问题描述】:
以下代码是如何工作的?
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];
请注意,
B是私有基础。这是如何运作的?请注意,
operator B*()是常量。为什么它很重要?为什么
template<typename T> static yes check(D*, T);比static yes check(B*, int);更好?
注意:它是boost::is_base_of 的精简版(删除了宏)。这适用于各种编译器。
【问题讨论】:
-
对模板参数和真正的类名使用相同的标识符是非常令人困惑的......
-
@Matthieu M.,我已经自己纠正了:)
-
前段时间我写了一个
is_base_of的替代实现:ideone.com/T0C1V它不适用于旧的GCC版本(GCC4.3工作正常)。 -
好的,我要去散步了。
-
这个实现不正确。
is_base_of<Base,Base>::value应该是true;这将返回false。
标签: c++ templates overloading implicit-conversion typetraits