以下代码如何工作?
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 …
我想检查给予模板的类型是否继承自项目中的基类.
它应该像以下示例中所期望的那样工作:
template< class T : public CBaseClass >
Run Code Online (Sandbox Code Playgroud)
我想知道,是否有任何优雅的方式(像这样)来检查模板参数是从给定的类派生的?一般来说:
template<class A, class B>
class MyClass
{
// shold give the compilation error if B is not derived from A
// but should work if B inherits from A as private
}
Run Code Online (Sandbox Code Playgroud)
另一个问题中提供的解决方案仅在B继承自A作为公共时才起作用:
class B: public A
Run Code Online (Sandbox Code Playgroud)
但是,我宁愿没有这样的约束:
class A{};
class B : public A{};
class C : private A{};
class D;
MyClass<A,B> // works now
MyClass<A,C> // should be OK
MyClass<A,D> // only here I need a compile error
Run Code Online (Sandbox Code Playgroud)
提前致谢!!!