字符串作为函数模版实参的特殊情况
2017-04-25 14:09
218 查看
#include "stdafx.h"
#include<iostream>
using namespace std;
/*
*匹配测试
*/
template<typename T>
int ref_fun(T & t1, T & t2)
{
return strlen(t1) - strlen(t2);
}
template<typename T>
int nonref_fun(T t1, T t2)
{
return strlen(t1) - strlen(t2);
}
/*
*类型测试
*/
template<typename T>
void Ref(T & t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}
template<typename T>
void nonRef(T t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}
int main()
{
//int a = ref_fun("abcd","abc");
//Error:没有与参数列表匹配的模版实例
//参数类型为(const char[5],const char[4])
int a = ref_fun("abcd","efgh");
//编译通过 为(const char[5],const char[5])
int b = nonref_fun("abcd", "abc");
//编译通过 为char *
/*
解释:对于引用类型的字符串参数编译器会自动转换成“字符常量数组”例如const char
,所以如果N值不同则两个字符串所对应的类型就不同,因此不能实例化同一个模版参数。而对于非引用
类型的字符串参数,编译器会自动将字符数组转换为字符指针类型,所以不同长度的字符串都会转换为相同额
字符指针类型,因此可以实例化同一个模版参数。
下面的代码是对于此结论的验证代码:
*/
//输出引用字符串的类型
Ref("abc");
//输出非引用字符串的类型
nonRef("abc");
}
#include<iostream>
using namespace std;
/*
*匹配测试
*/
template<typename T>
int ref_fun(T & t1, T & t2)
{
return strlen(t1) - strlen(t2);
}
template<typename T>
int nonref_fun(T t1, T t2)
{
return strlen(t1) - strlen(t2);
}
/*
*类型测试
*/
template<typename T>
void Ref(T & t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}
template<typename T>
void nonRef(T t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}
int main()
{
//int a = ref_fun("abcd","abc");
//Error:没有与参数列表匹配的模版实例
//参数类型为(const char[5],const char[4])
int a = ref_fun("abcd","efgh");
//编译通过 为(const char[5],const char[5])
int b = nonref_fun("abcd", "abc");
//编译通过 为char *
/*
解释:对于引用类型的字符串参数编译器会自动转换成“字符常量数组”例如const char
,所以如果N值不同则两个字符串所对应的类型就不同,因此不能实例化同一个模版参数。而对于非引用
类型的字符串参数,编译器会自动将字符数组转换为字符指针类型,所以不同长度的字符串都会转换为相同额
字符指针类型,因此可以实例化同一个模版参数。
下面的代码是对于此结论的验证代码:
*/
//输出引用字符串的类型
Ref("abc");
//输出非引用字符串的类型
nonRef("abc");
}
相关文章推荐
- 字符串作为函数模版实参的意外情况
- 字符串作为函数模版实參的意外情况
- 用字符串作为函数模版的实参
- C++基础——使用字符串作为函数模板的实参
- 类模版中使用模版函数,用于对特殊情况进行处理;(基于模板的使用时才物例化)
- 比较两个字符串的大小(两种方法,重点在介绍数组元素可以作为函数的实参)
- 使用字符串作为函数模板的实参
- python 函数返回值的特殊情况
- JS 字符串编码函数(解决URL特殊字符传递问题):escape()、encodeURI()、encodeURIComponent()区别详解
- encodeURI() 函数可把字符串作为 URI 进行编码。
- C++ template -- 字符串作为函数模板实参
- 流作为函数实参
- 二维数组作为函数的实参,定义函数形参的方法
- 10、 java 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 要求不能出现截半的情况
- 二维数组作为函数的实参,定义函数形参的方法
- 鸡啄米:C++编程入门系列之二十六(数组、指针和字符串:数组的存储与初始化、对象数组、数组作为函数参数)
- c++温故而知新---猜想:函数*p不可作为实参,求达人解惑!~
- 【你不知道】表达式中的隐式类型转换、无名对象作为函数实参
- 一个以引用作为参数的函数无法接收一个常量作为实参
- ASP.NET特殊字符串替换函数