读书人

请问C++11的std:is_abstractlt;gt;的实现原

发布时间: 2012-06-11 17:42:22 作者: rapoo

请教C++11的std::is_abstract<>的实现原理!
如题。我知道C++11的<type_traits>用模板和模板特化实现了一些类型判断的模板函数如
is_pointer,is_enum等基本数据类型的判断,并以此为基础实现is_compound,is_class等等

但是如何判断一个类型是否是is_abstract呢? 一个类型有virtual R f()=0;这样的纯虚函数声明,模板类型推导的机制是如何得到这个特性的?

还望各位专家解释!


[解决办法]
这种类型不能创建实例
[解决办法]

C/C++ code
template<class T>class is_abstract{    template<class U>    static char check_sig( U ( * )[1] );    template<class U>    static double check_sig( ... );    public:    enum {value = sizeof(check_sig<T>(0)) == sizeof(double) };};struct T0{    virtual void f() = 0;};struct T1: T0{    void f() {}};int main( int argc, char* argv[] ){    printf( "%d\n" , is_abstract<double>::value );    printf( "%d\n" , is_abstract<T0>::value );    printf( "%d\n" , is_abstract<T1>::value );    return 0;}
[解决办法]
探讨
我的解读错在哪里呢? 还请指点,谢谢!

[解决办法]
原理就是抽象类型不能有数组。。。。我给你贴个Boost的实现
C/C++ code
template<class T>struct is_abstract_imp2{   // Deduction fails if T is void, function type,    // reference type (14.8.2/2)or an abstract class type    // according to review status issue #337   //   template<class U>   static type_traits::no_type check_sig(U (*)[1]);   template<class U>   static type_traits::yes_type check_sig(...);   //   // T must be a complete type, further if T is a template then   // it must be instantiated in order for us to get the right answer:   //   BOOST_STATIC_ASSERT(sizeof(T) != 0);   // GCC2 won't even parse this template if we embed the computation   // of s1 in the computation of value.#ifdef __GNUC__   BOOST_STATIC_CONSTANT(std::size_t, s1 = sizeof(is_abstract_imp2<T>::template check_sig<T>(0)));#else#if BOOST_WORKAROUND(BOOST_MSVC_FULL_VER, >= 140050000)#pragma warning(push)#pragma warning(disable:6334)#endif   BOOST_STATIC_CONSTANT(std::size_t, s1 = sizeof(check_sig<T>(0)));#if BOOST_WORKAROUND(BOOST_MSVC_FULL_VER, >= 140050000)#pragma warning(pop)#endif#endif       BOOST_STATIC_CONSTANT(bool, value =       (s1 == sizeof(type_traits::yes_type)));}; 

读书人网 >C++

热点推荐