C++ decltype用法

一、decltype

decltype用于推断类型

template.h

#pragma once
#include <iostream>
#include <map>

template<typename T>
class CT2
{
public:
	//typename T::iterator iter;
	decltype(T().begin()) iter;
	void getbegin(T& tmpc)
	{
		iter = tmpc.begin();
	}
};

class A1
{
public:
	A1() 
	{
		std::cout << "A1 构造" << std::endl;
	}

	~A1()
	{
		std::cout << "A1 析构" << std::endl;
	}

	int func() const
	{
		std::cout << "A1 func" << std::endl;
		return 1;
	}
};

int &tf(int & i)
{
	return i;
}

double tf(double& d)
{
	return d;
}

template<typename T>
auto FuncTmp(T &tv)->decltype(tf(tv))//函数返回值后置,当tv为double &,推断的类型为double。当tv为int &,推荐的类型为int &
{
	return tf(tv);
}

main.cpp

#include <iostream>
#include "template.h"
using namespace std;
int main()
{
	using conttype = const std::vector<int>;//无论是const还好非const都可以通过decltype推荐出类型,const时为vettor<int>::const_iterator,非const时为vettor<int>::iterator,所以直接用typename T::iterator iter不行
	conttype myarr = { 10,30,40 };
	CT2<conttype> ct2;
	ct2.getbegin(myarr);

	decltype(A1().func()) aa = 2;//int aa = 2;并没有调用构造函数和析构函数

	int i = 19;
	FuncTmp(i);
	double d = 34.1f;
	FuncTmp(d);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值