一、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);
}