类型萃取,字面理解(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;
}

C++从类型萃取到特化

在这种假设中,我们可以认为特化后的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;
};

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
  • 2021-04-05
  • 2021-05-15
  • 2021-06-28
猜你喜欢
  • 2021-12-26
  • 2022-02-03
  • 2021-08-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案