c++ - std::is_base_of() 深度

标签 c++ c++11

我有这样的层次结构:

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 of Derived (10) without regard to cv-qualifiers or Base and Derived are not unions and name the same class type without regard to cv-qualifiers

基类定义如下(§10):

A class B is a base class of a class D if it is a direct base class of D or a direct base class of one of D's base classes.

所以是的,I1I3 的基类和 std::is_base_of<I1, I3>::value应该是 true .

关于c++ - std::is_base_of() 深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090216/

相关文章:

c++ - 在运行时生成可变参数列表

c++ - vector 重新分配后迭代器如何更新

c++ - 这个c++模板函数有什么问题

c++ - std::future 的错误用法?

c++ - 试图摆脱我的堆栈推送功能中的重复索引。我正在使用二维数组来模拟链表

c++ - 在 C++ 中将指向 char* 的 void* 转换为 std::string

c++ - 为什么 sizeof(str.substr(0,3).c_str()) 给我 8?

c++ - 阅读 C++ ifstream 两次?

c++ - 如何访问一系列常量变量作为常量数组

c++ - 在编译时生成 BitCount LUT