[c++] 带类型判断的模板

#include <iostream>
#include <type_traits>

template<typename T>
T* PrintType(int* x)
{
	if(std::is_same<T,int>::value) {
		std::cout << "int type" << std::endl;
		return reinterpret_cast<T*>(x);
	}
	else {
		std::cout << "not int type" << std::endl;
		return nullptr;
	}
}

template<typename T>
const T* PrintType(const int* x)
{
	if(std::is_same<T,int>::value) {
		std::cout << "const int type" << std::endl;
		return reinterpret_cast< const T*>(x);
	}
	else {
		std::cout << "not const int type" << std::endl;
		return nullptr;
	}
}


int main()
{
	int x=5;
	const int y=6;
	PrintType<int>(&x);
	PrintType<double>(&x);
	PrintType<int>(&y);
	PrintType<double>(&y);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/adream307/article/details/81020983
今日推荐