转载自CSDN
http://m.blog.csdn.net/force_eagle/article/details/4347329
模板函数
类型参数,template<typename T, class U>
非类型参数,template<int a,int &a>
模板定义必须在头文件中,源文件包含头文件即可
模板类:
就像范型STL 一样,实例化对象时,类型名后+ <>,显示实例化模板类型,要不然没法像函数那样传参,编译器才能推断处类型
#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T> class A // T是类型模板参数,常见的。
{
public:
A(T m_a) { cout << "AA\n"; };
};
template<int val> class B // int val是非类型模板参数,不常见的。一般用于指定常数。参见下面的用法。
{
public:
B()
{
int m_b[val];
cout << "BB\n";
};
};
int main()
{
A<double> a(3.14);
B<3> b3; // 声明带有3个元素的数组。
B<4> b4; // 声明带有4个元素的数组。
return 0;
}
——非类型参数
————只有全局的变量(包括指针和引用)才可以在< >内使用,如果是值的话还必须是常量。
// template.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
template <int &N>
struct _Ref
{
int getValue() { return N; }
};
template <int N>
struct _Val
{
int getValue() { return N; }
};
int global_a; // 全局变量默认为0
int const global_b = 1;
int main()
{
_Ref<global_a> instance1; // OK 引用类型必须是全局的
_Val<global_b> instance2; // OK 值类型必须是编译期常量
std::cout << instance1.getValue() << std::endl;
std::cout << instance2.getValue() << std::endl;
return 0;
}
————模板回调
利用函数指针进行回调
#include "stdafx.h"
#include <iostream>
template < class Class, typename ReturnType, typename Parameter > //三种类型参数
class SingularCallBack
{
public:
typedef ReturnType(Class::*Method)(Parameter); // 函数指针的定义:typedef int (*MYFUN)(int, int); 函数的别名就是MYFUN 这里是method
SingularCallBack(Class* _class_instance, Method _method) //Instance
{
//取得对象实例地址,及调用方法地址
class_instance = _class_instance;
method = _method;
};
ReturnType operator()(Parameter parameter) //仿函数,取一个参数,为A a
{
// 调用对象方法
return (class_instance->*method)(parameter); //调用的方法
};
ReturnType execute(Parameter parameter)
{
// 调用对象方法
return operator()(parameter);
};
private:
Class* class_instance;
Method method;
};
class A
{
public:
void output()
{
std::cout << "I am class A :D" << std::endl;
};
};
class B
{
public:
bool methodB(A a)
{
a.output();
return true;
}
};
int main()
{
A a;
B b;
SingularCallBack< B, bool, A >* cb;
cb = new SingularCallBack< B, bool, A >(&b, &B::methodB);
if ((*cb)(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
return 0;
}
有一种回调:
A a;
B b;
SingularCallBack< B, bool, A >* cb;
cb = new SingularCallBack< B, bool, A >(&b, &B::methodB);
if (cb->execute(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
回调:
A a;
B b;
SingularCallBack< B,bool,A >cb(&b,&B::methodB);
if(cb(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}