C++11中std::is_same和std::decay

https://blog.csdn.net/czyt1988/article/details/52812797
https://www.apiref.com/cpp-zh/cpp/types/decay.html

is_same用来判断两个类型是否相同;
decay用来将各种修饰符,包括引用、const等,都去除掉,也就是退化最原始的类型是啥,举个例子:
const int& a;
经过std::decay::type得到的就是int

template<typename T>
void typeCheck(T t)
{
	if (std::is_same<T, int>::value)
	{
		std::cout << "int type" << std::endl;
	}
	else
	{
		std::cout << "other type";
	}
}

int main()
{
	int x3 = 1;
	const int& x4 = x3;
	typeCheck<const int&>(x3);
}

这里的x3是int类型,const int&和他对比不是相同的类型。

template<typename T>
void typeCheck(T t)
{
	if (std::is_same<T, int>::value)
	{
		std::cout << "same" << std::endl;
	}
	else
	{
		std::cout << "different";
	}
}

int main()
{
	int x3 = 1;
	const int& x4 = x3;
	typeCheck(x4); //same int
	typeCheck<const int&>(x4); //显示指定,则different
}

将const int&退化为int,可以使用:

template<typename T>
void typeCheck(T t)
{
	if (std::is_same<std::decay<T>::type, int>::value)
	{
		std::cout << "same" << std::endl;
	}
	else
	{
		std::cout << "different";
	}
}

int main()
{
	int x3 = 1;
	const int& x4 = x3;
	typeCheck(x4); //same int
	typeCheck<const int&>(x4); //same int
}

你可能感兴趣的:(cpp,c++,算法,开发语言)