C++模板通常有两种形式:函数模板和类模板。函数模板针对:参数类型不同的函数;类模板针对:数据成员和成员函数类型不同的类。
模板的声明或定义只能在全局,命名空间或类范围内进行,不能在局部、函数内进行。
函数模板
template <class 形参名,class 形参名,……>返回类型 函数名(参数列表){
//函数体
}//class可用typename代替
//例如:
template <class T> void swap(T&a, T&b){}
类模板
template<class 形参名, class 形参名,……> class 类名{
//...
};
//例如:
template<class T>class A{
public:
T a;
T b;
T hy(T c, T& d);
};
实例展示
template<typename Iterator, typename T> struct accumulate_block {
void operator()(Iterator first, Iterator last, T& result) {
result = std::accumulate(first, last, result);
}
};//类模板:accumulate_block
template<typename Iterator, typename T>
T parallel_accumulate(Iterator first, Iterator last, T init) {
unsigned long const length = std::distance(first, last);
if(!length) return init;
unsigned long const min_per_thread=25;
unsigned long const max_threads = (length+min_per_thread-1)/min_per_thread;
unsigned long const hardware_threads = std::thread::hardware_concurrency();
unsigned long const num_threads = std::min(hardware_threads!=0?hardware_threads:2,max_threads);
unsigned long const block_size = length/num_threads;
std::vector<T> results(num_threads);
std::vector<std::thread> threads(num_threads-1);
Iterator block_start = first;
for(unsigned long i = 0; i < (num_threads-1); ++i) {
Iterator block_end = block_start;
std::advance(block_end, block_size);
threads[i] = std::thread(
accumulate_block<Iterator, T>(), block_start, block_end, std::ref(results[i]));
block_start = block_end;
}
accumulate_block<Iterator, T>()(
block_start, last, results[num_threads-1]);
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
return std::accumulate(results.begin(), results.end(), init);
}//函数模板:T parallel_accumulate(Iterator first, Iterator last, T init);