正文

模板杂记2007-09-27 10:29:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/29693.html

分享到:

本文专门记录学习过程中碰到的关于模板的一些技巧:

1. 使用IsOfClassType类判断一个数据类型是否是class。

template<typename T> class IsOfClassType {

public:
 template<typename U> static char check(int U::*);
 template<typename U> static float check(...);

public:
 enum { Result = sizeof(check<T>(0)) };

};

 

2.

template <typename _T>
class A{};

class B: public A< B >{
};

 

3.强制类型转换

template<typename dst_type,typename src_type>
dst_type union_cast(src_type src) {
    union {
        src_type src;
        dst_type dst;
    } u = {src};
  return u.dst;
}

4.编译期计算数组元素个数

template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper( _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) sizeof(*__countof_helper(_Array))


5.判断类里面是否包含某个函数(有点类似__if_exists)

template<class CLS>

struct if_bar_exists

{

private:

    struct Exists    { char x; };

    struct NotExists { char x[2]; };

    template< void (CLS::*)( void ) >

    struct Param;


    template<class T>

    static Exists    detect( Param<&T::bar>* );

    template<class T>

    static NotExists detect( ... );


public:

    static const bool val = ( sizeof(detect<CLS>(0)) == sizeof(Exists) );

};


struct foo1

{

    void bar( void );

};

struct foo2

{

    void bar( int );

};


int main()

{

    std::cout << if_bar_exists<foo1>::val << std::endl;

    std::cout << if_bar_exists<foo2>::val << std::endl;


    return 0;

}

阅读(2006) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册