三类元素可以做为模板变量:
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");
}