C++ - 非类型模板参数(nontype template parameters) 使用 及 代码

非类型模板参数(nontype template parameters) 使用 及 代码

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17219921

 

非类型模板参数(nontype template parameters), 可以使用整型类型(integral type),指针(pointer) 或者是 引用(reference);

绑定非类型整数形参(nontype integral parameter) 的 实参(argument) 必须是常量表达式(constant expression, constexpr);

不能普通的局部对象或者动态对象 绑定 指针或引用的非类型形参, 可以使用全局类型进行绑定;

关于类模板(class template)中非类型模板参数的写法,参见: http://en.cppreference.com/w/cpp/language/class_template

下面例子包含了模板类型是 整型, 指针, 引用, 函数指针 的函数的常见写法;

注意指针和引用的实参是全局变量;

代码如下:

 

//=====================================
// Name        : CppPrimer.cpp
// Author      : Caroline
// Version     : 1.0
// Description : Example, UTF-8
//=====================================

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

//整型模板
template<unsigned N, unsigned M>
bool compare (const char (&p1)[N], const char (&p2)[M])
{
	std::cout << "size : " << N << " " << M << std::endl;
	return strcmp(p1, p2);
}

//指针
template<const char* C>
void pointerT(const char* str){
	std::cout << C << " " << str << std::endl;
}

//引用
template<char (&ra)[9]>
void referenceT(const char* str){
	std::cout << ra << " " << str << std::endl;
}

char ca[] = "Caroline"; //初始化指针
char cr[9] = "Caroline"; //初始化引用, 包含一个结尾符号

void f(const char* c) {std::cout << c << std::endl; }

//函数指针
template<void (*F)(const char*)>
void fpointerT(const char* c) {
	F(c);
}

int main(void)
{
	if(compare("Caroline", "Wendy")) {
		std::cout << "Caroline is long." << std::endl;
	} else {
		std::cout << "Wendy is long." << std::endl;
	}

	//无法使用局部变量或者动态变量作为模板参数
	pointerT<ca>("Wendy"); //指针

	referenceT<cr>("Wendy"); //引用

	fpointerT<f>("Caroline Wendy"); //函数指针

	return 0;
}


输出:

 

 

size : 9 6
Caroline is long.
Caroline Wendy
Caroline Wendy
Caroline Wendy

 

 

 

 

 

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CarolineSpike

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值