值模板参数Value Template Parameters

11 篇文章 0 订阅

模板通常使用类型作为参数,但它们也可以使用值。使用类型和可选名称声明一个值模板参数,方式与声明函数参数类似。值模板参数仅限于可以指定编译时常量的类型是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]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值