《C++ Templates》:有关const、引用、指针的一些函数模板实参推导的例子

1.T按值传递

最简单的模板例子:

cpp 复制代码
template<typename T>
void func(T x) {
    std::cout << typeid(T).name() << std::endl;
    x = 20;
    cout << x;
}

这种情况下,T永远不会被推导成带顶层const或引用的类型

【顶层const即变量本身不能被修改,例如const int和const int &都是变量本身不能被修改的情况】

这种情况,T是int类型

cpp 复制代码
int a = 10;
int& b = a;
func(b);

这种情况,T还是int类型

cpp 复制代码
int a = 10;
const int& p = a;
func(p);

这种情况,T还是int类型

cpp 复制代码
const int a = 10;
func(a);

这种情况,T是int *

cpp 复制代码
int* p = nullptr;
func(p);

而这种情况,T还是int * (因为int *const p的意思是p是一个指向int类型的指针,而且指针p的值不能改变,故该const是顶层const)

cpp 复制代码
int *const p = nullptr;
func(p);

而底层const会被保留

【底层const即变量指向的内容不能被修改,典型例子是const int *p=&a,变量p的const就是底层const】

故这种情况下T是const int *(int const *)类型

cpp 复制代码
template<typename T>
void func(T x) {
    std::cout << typeid(T).name() << std::endl;
}
int main()
{
    const int *a =nullptr;
    func(a);
}

顺便提一下,这种情况T依然是const int *,因为T是不会推导出引用的

cpp 复制代码
const int* a = nullptr;
const int *&p =a;
func(p);

2.T &

T 仍然不会是引用

但是T会保留顶层const

func函数如下

cpp 复制代码
#include <type_traits>
using namespace std;
template<typename T>
void func(T &x) {
	if (std::is_reference<T>::value) {//可以判断T是否是引用类型
		std::cout << "T is a reference type." << std::endl;
	}
	else {
		std::cout << "T is not a reference type." << std::endl;
	}
    std::cout << typeid(T).name() << std::endl;//即使T真是int &,typeid(T).name()也只会输出int,所以要上面的判断帮忙
    x = 20;
    cout << x << endl;
}

T是int;x的类型是int &,运行过后a的值也是20;

cpp 复制代码
int a = 10;
int& b = a;
func(b);

T是const int;x的类型是const int &

cpp 复制代码
template<typename T>
void func(T &x) {
	if (std::is_reference<T>::value) {
		std::cout << "T is a reference type." << std::endl;
	}
	else {
		std::cout << "T is not a reference type." << std::endl;
	}
	if (std::is_const<T>::value) {//检测const
		std::cout << "T is a const type." << std::endl;
	}
	else {
		std::cout << "T is not a const type." << std::endl;
	}
    std::cout << typeid(T).name() << std::endl;
    //x = 20;由于x是const int &,不可以给x赋值
    cout << x << endl;
}
int a=10;
const int& b = a;
func(b);
相关推荐
樱木Plus1 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
哇哈哈20218 天前
信号量和信号
linux·c++
多恩Stone8 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马8 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode