[英]Using std::is_base_of with decltype on class hierarchy
For the purposes of brevity, this is the simplified hierarchy: 为了简洁起见,这是简化的层次结构:
class IBase
{
public:
virtual ~IBase() = 0 { };
}; // eo IBase
class IDerived : public virtual IBase
{
public:
virtual ~IDerived() = 0 { };
}; // eo IDerived
class Base : public virtual IBase
{
public:
Base() { };
virtual ~Base() { };
}; // eo Base
class Derived : public IDerived
, public Base
{
}; // eo Derived
And a function to determine if a particular pointer to a class implements the passed "interface": 一个确定类的特定指针是否实现了传递的“接口”的函数:
template<typename T>
bool same(IBase* base)
{
if(std::is_base_of<T, decltype(*base)>::value)
return true;
return false;
};
And the sample: 和示例:
IDerived* i(new Derived());
bool isSame = same<IDerived>(i);
I am aware I may me mis-using decltype
here. 我知道我可能会在这里误用decltype
。 It appears whatever I try, std::is_base_of<B,D>::value
is always false
. 看来我尝试了什么, std::is_base_of<B,D>::value
始终为false
。 What I want this function to do is, answer the question: 我要此功能要做的是,回答以下问题:
Does the object pointed to, derive from the type ( T
) passed as the template parameter? 对象所指向的对象是否源自作为模板参数传递的类型( T
)?
decltype
, like sizeof
, is a compile-time construct. 像sizeof
一样, decltype
是一个编译时构造。 That means, decltype(*base)
will give the static type of the expression *base
which is IBase
. 这意味着decltype(*base)
将给出表达式*base
的静态类型,即IBase
。 So what you intend to achieve cannot be done this way. 因此,您打算实现的目标无法通过这种方式完成。
I would suggest this solution: 我建议这种解决方案:
template<typename T>
bool same(IBase* base)
{
return dynamic_cast<T*>(base) != nullptr;
};
template<typename T>
bool same(IBase* base)
{
if(std::is_base_of<T, decltype(*base)>::value)
This can't work. 这行不通。 decltype(*base)
would be IBase
(always), so it would never reflect the runtime type of base
. decltype(*base)
始终是IBase
,因此它永远不会反映base
的运行时类型。
Probably the best you can do is dynamic_cast<T*>(base)!=0
. 可能最好的办法是dynamic_cast<T*>(base)!=0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.