100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板部分特例化

C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板部分特例化

时间:2021-10-14 00:17:11

相关推荐

C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板部分特例化

1. 类模板的部分特例化(partial specialization)

类模板的特例化不必为所有模板参数提供实参(可以只指定一部分而非所有模板参数, 或是参数的一部分而非全部特性)。类模板的部分特例化本身是一个模板, 使用它时用户还必须为那些在特例化版本中未指定的模板参数提供实参。

1.1

//原始的、 最通用的版本 template <class T> struct remove_reference {typedef T type;};// 部分特例化版本, 将用于左值引用和右值引用template <class T> struct remove_reference<T &> // 左值引用 {typedef T type;};template <class T> struct remove_reference<T &&> // 右值引用{typedef T type;};

三个变量 a、 b 和 c 均为 int 类型。

int i;//decltype(42)为int, 使用原始模板remove_reference<decltype(42)>::type a;//decltype (i)为int&, 使用第一个(T&) 部分特例化版本remove_reference<decltype(i)>::type b;//decltype(std::move(i))为int &&, 使用第二个即T&&)部分特例化版本remove_reference<decltype(std::move(i))>::type c;

2. 特例化成员而不是类

可以只特例化特定成员函数而不是特例化整个模板

template <typename T> struct Foo {Foo(const T &t = T()):mem(t){}void Bar(){/*...*/ }T mem;// Foo 的其他成员}//特例化一个模板template<> void Foo<int>::Bar() //特例化 Foo<int>的成员 Bar{//进行应用于int的特例化处理}Foo<string> fs;//实例化 Foo<string>::Foo( )fs.Bar();// 实例化 Foo<string>::Bar( )Foo<int> fi; //实例化 Foo<int>::Foo( )fi.Bar();//使用我们特例化版本的 Foo<int>::Bar( )

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。