#include <iostream>
//用于标记不同的类型
struct _false_type {};
struct _true_type {};
//-------------------------------使用模板特例化功能,在不同类型内放置不同的定义类型------------------
template<typename value_type>
struct type_traits
{
typedef _true_type Can_Print;
};
class MyType
{
};
//此处使用到模板特例化
template<>
struct type_traits<MyType>
{
typedef _false_type Can_Print;
};
//相当于中转站,根据不同的类型转到不同的实际操作
template<typename value_type>
void Print(value_type value)
{
typedef typename type_traits<value_type>::Can_Print Can_Print;
_Print(value, Can_Print());
}
//-----------------------------实际操作如何进行-------------------------
template<typename value_type>
void _Print(value_type value, _false_type)
{
std::cout << "this type can't printed!" << std::endl;
}
template<typename value_type>
void _Print(value_type value, _true_type)
{
std::cout << value << std::endl;
}
//主函数
int main(int argc, char const *argv[])
{
int x = 0;
Print(x);
MyType m;
Print(m);
std::cin.get();
return 0;
}
简单的一个C++中traits功能的实现例子
最新推荐文章于 2024-06-09 16:27:48 发布