读书笔记《C++设计新思维》(7) std::type_info类的包装类

std::type_info类可以在执行期间查询对象型别,但使用起来比较麻烦。为此定义了wrapper

下面的代码出自 Loki库:
总得来说是提供了std::type_info的所有成员函数;
提供了value语义,即public copy构造函数和public assignment操作符;
定义了 operator< 和 operator== 等

namespace  Loki
{
/**/////////////////////////////////////////////////////////////////////////////////
// class TypeInfo
// Purpose: offer a first-class, comparable wrapper over std::type_info
/**/////////////////////////////////////////////////////////////////////////////////

    
class TypeInfo
    
{
    
public:
        
// Constructors
        TypeInfo(); // needed for containers
        TypeInfo(const std::type_info&); // non-explicit

        
// Access for the wrapped std::type_info
        const std::type_info& Get() const;
        
// Compatibility functions
        bool before(const TypeInfo& rhs) const;
        
const char* name() const;

    
private:
        
const std::type_info* pInfo_;
    }
;
    
// Implementation
    
    inline TypeInfo::TypeInfo()
    
{
        
class Nil {};
        pInfo_ 
= &typeid(Nil);
        assert(pInfo_);
    }

    
    inline TypeInfo::TypeInfo(
const std::type_info& ti)
    : pInfo_(
&ti)
    
{ assert(pInfo_); }
    
    inline 
bool TypeInfo::before(const TypeInfo& rhs) const
    
{
        assert(pInfo_);
        
return pInfo_->before(*rhs.pInfo_) != 0;
    }


    inline 
const std::type_info& TypeInfo::Get() const
    
{
        assert(pInfo_);
        
return *pInfo_;
    }

    
    inline 
const char* TypeInfo::name() const
    
{
        assert(pInfo_);
        
return pInfo_->name();
    }


// Comparison operators
    
    inline 
bool operator==(const TypeInfo& lhs, const TypeInfo& rhs)
    
return (lhs.Get() == rhs.Get()) != 0; }

    inline 
bool operator<(const TypeInfo& lhs, const TypeInfo& rhs)
    
return lhs.before(rhs); }

    inline 
bool operator!=(const TypeInfo& lhs, const TypeInfo& rhs)
    
return !(lhs == rhs); }    
    
    inline 
bool operator>(const TypeInfo& lhs, const TypeInfo& rhs)
    
return rhs < lhs; }
    
    inline 
bool operator<=(const TypeInfo& lhs, const TypeInfo& rhs)
    
return !(lhs > rhs); }
     
    inline 
bool operator>=(const TypeInfo& lhs, const TypeInfo& rhs)
    
return !(lhs < rhs); }
}

你可能感兴趣的:(读书笔记《C++设计新思维》(7) std::type_info类的包装类)