专业编程基础技术教程

网站首页 > 基础教程 正文

C++模板参数推导(c++模板的作用)

ccvgpt 2024-08-03 12:31:51 基础教程 64 ℃
#include <cstdio>
#include <iostream>
#include <boost/type_index.hpp>

using namespace std;
using boost::typeindex::type_id_with_cvr;

template<typename T>
T&& forward(T& para)//标准库 类似这样实现
{
	return static_cast<T&&>(para);
}

void f(int& a)
{

}

void f(int&& a)
{

}

template<class T>
void te(T a)//推导 T为源类型
{
	//cout << "T type:" << type_id_with_cvr<T>().pretty_name() << endl;
 	//cout << "param type:" << type_id_with_cvr<decltype(a)>().pretty_name() << endl;
}

template<class T>
void tu(T& a)//推导 T为 const类型 或 非const
{
	//cout << "T type:" << type_id_with_cvr<T>().pretty_name() << endl;
 	//cout << "param type:" << type_id_with_cvr<decltype(a)>().pretty_name() << endl;
}

template<class T>
void tcu(const T& a)//推导 T为  非const
{
	//cout << "T type:" << type_id_with_cvr<T>().pretty_name() << endl;
 	//cout << "param type:" << type_id_with_cvr<decltype(a)>().pretty_name() << endl;
}

template<class T>
void rtcu(T&& a)//推导 T为 const类型 或 非const
{
	cout << "T type:" << type_id_with_cvr<T>().pretty_name() << endl;
 	cout << "param type:" << type_id_with_cvr<decltype(a)>().pretty_name() << endl;
  //f(std::forward<T>(a));    //完美转发
}


int main()
{
   	int a;
    const int b = 20;
    //测试模板 T
    te(1);//T type:int         						 param type:int
  	te(a);//T type:int         						 param type:int
    te(b);//T type:int         						 param type:int
	  
    //测试模板 T&
    //tu(1);
  	tu(a);//T type:int         						 param type:int&
    tu(b);//T type:int const    			 param type:int const&
    
    //测试模板 const T&
  	tcu(1);//T type:int       					  param type:int const&
    tcu(a);//T type:int        						param type:int const&
    tcu(b);//T type:int        					  param type:int const&

    //测试模板 T&&
  	rtcu(1);//T type:int           			  param type:int&&
    rtcu(a);//T type:int&          		  param type:int&
    rtcu(b);//T type:int const&     param type:int const&
}

Tags:

最近发表
标签列表