我有这样的层次结构:
namespace MyService{
class IBase
{
public:
virtual ~IBase(){}
protected:
IPointer *_somePointer;
};
}
class IInterface: public MyService::IBase
{
public:
virtual ~IInterface(){}
virtual std::string get() const = 0;
};
class ConcreteClass: public IInterface
{
public:
std::string get() const
{
bool isNull = (_somePointer == NULL);
return "Hello";
}
};
bool isBase = std::is_base_of<IBase, ConcreteClass>::value;
我需要检查 I3 是否派生自 I1。但是 std::is_base_of() 对我来说效果不佳——它返回 false。 目标是添加到任何类 IBase 并检查任何类是否在其层次结构中有 IBase
找到了问题,但没有解决。我的代码是:
template<class Base, class Derived>
bool IsDerivedFromBase()
{
if( std::tr1::is_fundamental<Base>::value )
throw MyService::Exceptions::ETypeTraitsInvalidArgument( "Base class can't be POD" );
if( std::tr1::is_fundamental<Derived>::value )
throw MyService::Exceptions::ETypeTraitsInvalidArgument( "Derived class can't be POD" );
bool a = std::tr1::is_base_of<Base, Derived>::value;
return a;
}
我有一个这样的
bool a = std::is_base_of<MyService::IBase, SomeInterface>::value; // true
a = IsDerivedFromBase<MyService::IBase, SomeInterface>(); // false
最佳答案
这会输出 true
使用 G++ 4.7:
class I1{};
class I2: public I1{};
class I3: public I2{};
int main(int argc, const char* argv[])
{
std::cout << std::boolalpha
<< std::is_base_of<I1, I3>::value
<< std::endl;
return 0;
}
注意 std::is_base_of<I1, I3>::value
等同于实例化一个 std::is_base_of<I1, I3>
类型的对象并将其转换为 bool
.
我相信这样做是准确的。 std::is_base_of<Base, Derived>
被定义为具有条件 (§20.9.6):
Base
is a base class ofDerived
(10) without regard to cv-qualifiers orBase
andDerived
are not unions and name the same class type without regard to cv-qualifiers
基类定义如下(§10):
A class
B
is a base class of a classD
if it is a direct base class ofD
or a direct base class of one ofD
's base classes.
所以是的,I1
是 I3
的基类和 std::is_base_of<I1, I3>::value
应该是 true
.
关于c++ - std::is_base_of() 深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090216/