模板通常使用类型作为参数,但它们也可以使用值。使用类型和可选名称声明一个值模板参数,方式与声明函数参数类似。值模板参数仅限于可以指定编译时常量的类型是bool、char、int等,但不允许使用浮点类型、字符串字面值和类。
#include <iostream>
#include <array>
#include <utility>
template<class T, int N>
class Polygon{
public:
Polygon(const std::array<std::pair<T, T>, N>& pts){
for(int i = 0; i < N; ++i){
points_[i].x_ = pts[i].first;
points_[i].y_ = pts[i].second;
}
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
virtual ~Polygon(){
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
struct Point{
T x_;
T y_;
};
void draw(){
for(int i = 0; i < N; ++i){
std::cout << points_[i].x_ << ", " << points_[i].y_ << std::endl;
}
}
private:
Point points_[N];
};
/* N=1的特化版本 */
template<class T>
class Polygon<T,1>{
public:
Polygon(){
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
virtual ~Polygon(){
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
struct Point{
T x_;
T y_;
};
void draw(){
std::cout << "One point only!\n";
}
private:
Point points_[1];
};
int main() {
std::array<std::pair<float, float>, 5> pts = {std::pair<float, float>{1.f,2.f},std::pair<float, float>{3.f,4.f},std::pair<float, float>{4.f,5.f},std::pair<float, float>{6.f,7.f},std::pair<float, float>{7.f,8.f}};
Polygon<float,5> poly1(pts);
poly1.draw();
Polygon<int,1> poly2;
poly2.draw();
}
输出:
Polygon<T, N>::Polygon(const std::array<std::pair<T, T>, N>&) [with T = float; int N = 5]
1, 2
3, 4
4, 5
6, 7
7, 8
Polygon<T, 1>::Polygon() [with T = int]
One point only!
Polygon<T, 1>::~Polygon() [with T = int]
Polygon<T, N>::~Polygon() [with T = float; int N = 5]