C++从类型萃取到特化

本文深入探讨C++中的模板特化概念,包括全特化与偏特化,以及如何通过类型特质(type traits)区分处理内置类型与自定义类型。通过具体代码示例,展示了特化在性能优化上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类型萃取,字面理解(type traits)

#include<iostream>
using namespace std;

template<class T>
class A
{
public:
	A()
		:a(0)
	{
		cout << "初始的模板" << endl;
	}

	T a;
};

template<>
class A<int>
{
public:
	A()
		:a(0)
	{
		cout << "全特化" << endl;
	}
	int a;
};

void test_template()
{
	A<char> first;
	A<int> second;
}

在这种假设中,我们可以认为特化后的int处理会比其他类型使用初始模板好,于是使用了特化。

这个是全特化,自然,还有偏特化。

template< class T>
class Test<int,T>
{
public:

    Test()
    {
        cout << "Test 偏特化" << endl;
    }
};
//偏特化

下面是STL中针对不同类型特化,很好理解,一个自定义对象的操作和一个人普通内置类型int的操作就应该不一样,而模板接口接受参数时,统一是自定义T接受,然后处理上分开处理,便是C++的性能优势。 

// 代表内置类型
struct __true_type {};
// 代表自定义类型
struct __false_type {};
template <class type>
struct __type_traits
{
typedef __false_type is_POD_type;
};
// 对所有内置类型进行特化
template<>
struct __type_traits<char>
{
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<signed char>
{
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned char>
{
typedef __true_type is_POD_type;
};

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值