C++ 基本type traits

49 阅读1分钟

type_traits.h

#pragma once
namespace wr
{
	struct false_type {
		static constexpr bool value = false;
	};
	struct true_type {
		static constexpr bool value = true;
	};

	template<class T>
	struct is_int:false_type {

	};

	template<>
	struct is_int<int>:true_type {//特化

	};

	//模板处理
	template<class T>
	struct remove_ref {
		using type = T;
	};
	template<class T>
	struct remove_ref<T &> {
		using type = T;
	};
	template<class T>
	struct remove_ref<T &&> {
		using type = T;
	};

	template<class T>
	struct remove_const {
		using type = T;
	};
	template<class T>
	struct remove_const<const T> {
		using type = T;
	};
	
	template<class T>
	struct is_int_handler:is_int<typename remove_ref<typename remove_const<T>::type>::type> {

	};

	//也可直接对于每个特化使用继承的方法
	template<>
	struct is_int<const int> :is_int<int> {};
	template<>
	struct is_int<int&> :is_int<int> {};
}

main.cpp

#include"type_traits.h"
int main() {
	using namespace wr;
	cout << is_int<float>::value << endl;
	cout << is_int<int>::value << endl;
	cout << is_int<int&>::value << endl;
	cout << is_int_handler<int&>::value << endl;
	cout << is_int_handler<const int>::value << endl;
	//cout << is_int<int&>::value << endl;
}