当前位置: 首页 > news >正文

值模板参数Value Template Parameters

模板通常使用类型作为参数,但它们也可以使用值。使用类型和可选名称声明一个值模板参数,方式与声明函数参数类似。值模板参数仅限于可以指定编译时常量的类型是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]
http://www.lryc.cn/news/343881.html

相关文章:

  • Splashtop 荣获 TrustRadius 颁发的“2024年度最受欢迎奖”
  • 使用python将`.mat`文件转换成`.xlsx`格式的Excel文件!!
  • python基础 面向练习学习python1
  • Ubuntu安装Docker和Docker Compose
  • 【linux软件基础知识】-死锁问题
  • C#面:简要谈对微软.NET 构架下 remoting 和 webservice 两项技术的理解以及实际中的应用
  • 《21天学通C++》(第十九章)STL集合类(set和multiset)
  • CSDN上是不是有机器人点赞和收藏?
  • 头歌C语言课程实验(递归函数、嵌套函数)
  • 树莓派的几种登录方式、及登录失败解决方式
  • 数据库中视图的知识点
  • aardio封装库) 微软开源的js引擎(ChakraCore)
  • LeetCode-hot100题解—Day6
  • 【Linux】gcc/g++的使用
  • 2024-5-3学习笔记 虚拟继承原理
  • C语言什么是“野指针”?
  • LeetCode--所有质数、质数对
  • JavaScript异步编程——05-回调函数
  • JAVA基础之jsp标准标签
  • VM16激活码以及连接centos7过慢的问题
  • MySQL 迁移到 Oracle 需要注意的问题
  • 【数字经济】上市公司供应链数字化数据(2000-2022)
  • 通过AOP实现项目中业务服务降级功能
  • LeetCode:盛最多水的容器
  • 阿里云 OSS桶对象存储攻防
  • 外网禅道配置
  • MM模块学习一(供应商创建,物料类型的定义及功能)
  • 玩comfyui踩过的坑之使用ComfyUI_Custom_NODES_ALEKPET翻译组件问题
  • (类)偏特化Partial Specialization
  • TypeScript 基础学习笔记:interface 与 type 的异同