C++ Traits运用实例

问题描述

需要把数据类型分为三类,比如float,double是一类,int, char是一类,其他的包括自定义类型是一类。

解决方法

// template_test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

template<typename T>
struct TypeTraits
{
	static const int data_type = 0;	//这里的static非常关键
};

template<>
struct TypeTraits<char>
{
	static const int data_type = 1;
};

template<>
struct TypeTraits<int>
{
	static const int data_type = 1;
};

template<>
struct TypeTraits<float>
{
	static const int data_type = 2;
};

template<>
struct TypeTraits<double>
{
	static const int data_type = 2;
};

//没有偏特化为1或2的情况走下面的operator
template<int data_type>
class TypeGroup
{
public:
	template<typename T>
	string operator()(T &t)
	{
		cout <<"default: "<< t << endl;
		return "0";
	}
};

//char 或者 int 走下面的code
template<>
class TypeGroup<1>
{
public:
	template<typename T>
	string operator()(T &t)
	{
		cout << "int/char: "<<(int)t << endl;
		return "1";
	}
};

//double走下面的code
template<>
class TypeGroup<2>
{
public:
	template<typename T>
	string operator()(T &t)
	{
		cout << "double: " << setprecision(2) << t << endl;
		return "2";
	}
};

template<typename T>
class Test
{
public:
	void operator()(T t)
	{
		TypeGroup<TypeTraits<T>::data_type>test;
		test(t);
	}

};


int main()
{
	
	TypeTraits<int> a;
	cout << a.data_type << endl;
	TypeTraits<double> b;
	cout << b.data_type << endl;
	TypeTraits<string> c;
	cout << c.data_type << endl;

	Test<char> d;
	d(10);
	Test<double> e;
	e(3.1415);
	Test<string> f;
	f("hello world!");

    return 0;
}


输出结果如下:
在这里插入图片描述

3. 参考文献

下面两篇文章都讲的通俗易懂。

  1. 十分钟让你对C++ Traits大彻大悟
  2. C++ Trait特性萃取
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值