首页 > C/C++ > C++ Template Non-type Parameter

C++ Template Non-type Parameter

C++的template可以传入普通的参数,像给普通函数传入参数一样。可能平时并不多见,但这是完全可以的,因为好久没看这方面的东西,对这样的写法表示大为吃惊。也难怪,笔记本散热不好,《Effective C++》被我拿来垫笔记本了,而《More Effective C++》一直放在枕头旁边……翻了一下,书上都有提及这样的写法。

Besides the template arguments that are preceded by the class or typename keywords , which represent types, templates can also have regular typed parameters, similar to those found in functions. As an example, have a look at this class template that is used to contain sequences of elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
 
template <class T, int N>
class mysequence {
    T memblock [N];
  public:
    void setmember (int x, T value);
    T getmember (int x);
};
 
template <class T, int N>
void mysequence<T,N>::setmember (int x, T value) {
  memblock[x]=value;
}
 
template <class T, int N>
T mysequence<T,N>::getmember (int x) {
  return memblock[x];
}
 
int main () {
  mysequence <int,5> myints;
  mysequence <double,5> myfloats;
  myints.setmember (0,100);
  myfloats.setmember (3,3.1416);
  cout << myints.getmember(0) << '\n';
  cout << myfloats.getmember(3) << '\n';
  return 0;
}

It is also possible to set default values or types for class template parameters.(设置参数的默认值也是可以的。)

相关链接:
Non-type Template Arguments
Non-type parameters for templates


觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> C++ Template Non-type Parameter
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: C/C++ 标签: , , ,