Meta programming 学习 <二> Template parameter

    三类元素可以做为模板变量:

 Type template parameter

    Non-type template parameter: int/short/char/enum , object ptr (必须指向全局/静态对象), function ptr, object refrence.

    template as template parameter

    具体参见如下代码:

#include<iostream>

//all kinds of template parameters

//1. type template parameter
template<class T>
struct tpl_type{ typedef T type;};


//2. Non-type tmeplate paramter
//2.1 int
template<int N>
struct tpl_int
{
       enum {value = N};
};

//2.2 enum
enum EType
{
     e_type_0 = 0,
     e_type_1 = 1
};

template<EType eType>
struct tpl_enum
{
   static const EType value = eType;
};

//2.3 object ptr;
class A {};
template<A* ptr>
struct tpl_obj_ptr
{
       static A* get_value(){ return ptr;}
};
A g_a;

//2.4 func ptr
typedef int (*fun_ptr)(int);
int fun_1(int c){ std::cout << c << std::endl; }

template<fun_ptr f_ptr>
struct tpl_fun_ptr
{
       static fun_ptr get_value(){ return f_ptr; }
};

//2.5 obj_ref
template<A& ref>
struct tpl_obj_ref
{
       static A& get_value(){ return ref;}
};

//template template parameter
template< class T1, template<class T> class inner_tpl >
struct tpl_tpl
{
       typedef inner_tpl<T1> type;
};


int main()
{
    //type template parameter
    tpl_type<int>::type tpl_type_instance;
    tpl_type< tpl_type<int> >::type tpl_type_instance_2;
    
    //non-type template paramter
    tpl_int<3>::value;
    
    tpl_enum<e_type_1>::value;
    
    tpl_obj_ptr< &g_a >::get_value();
    
    tpl_obj_ref< g_a >::get_value();
    
    (tpl_fun_ptr<fun_1>::get_value())(3);
    
    //template template parameter
    tpl_tpl<int,tpl_type>::type tpl_tpl_instance;
    
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值