C++11-模板改进

1.类型别名

旧语法:typedef 源类型 目标类型;(源类型必须是具体的类型)

typedef unsigned int unit_t;

新语法:using 目标类型=源类型;(源类型可以是模板)

using unit_t=unsigned int;

旧语法中的typedef其源类型必须是具体类型,而新语法中的using其源类型除了具体类型以外换可以是模板或者半模板

#include <iostream>
#include <typeinfo>
using namespace std;
typedef unsigned int unit_t;
using UNIT_T=unsigned int;
template <typename A,typename B>
class X
{};
typedef X<int,double> xid_t;
template <typename A,typename B>
//全模板
using x_t=X<A,B>;
template <typename B>
//半模板
using xi_t=X<int,B>;

using XID_T=X<int,double>;
int main(void)
{
cout<<typeid(unsigned int).name()<<endl;//j
cout<<typeid(unit_t).name()<<endl;//j
cout<<typeid(unsigned int).name()<<endl;//j
cout<<typeid(UNIT_T).name()<<endl;//j
cout<<typeid(xid_t).name()<<endl;//j
cout<<typeid(x_t<int,double>).name()<<endl;//j
cout<<typeid(xi_t<double>).name()<<endl;//j
cout<<typeid(XID_T).name()<<endl;//j
return 0;
}

 

2.函数模板和类模板一样,都可以带有缺省参数,而且如果满足隐式推断的条件,函数模板的缺省值不一定非要写在参数表的最后

(函数模板的部分参数可以通过隐式推断得出),类模板没有隐式推断,无法隐式推断的函数模板参数取缺省值,否则取隐式推断的类型,只要隐式推断生效,

模板参数的缺省值即被忽略

#include <iostream>

#include <typeinfo>
using namespace std;
template<typename A = int, typename B = double,typename C = string>
void foo (void)
{
cout << typeid (A).name () << ' '<< typeid (B).name () << ' '<< typeid (C).name () << endl;
}
template<typename A = int, typename B,typename C = string>
void bar (B b)
{
cout << typeid (A).name () << ' '<< typeid (B).name () << ' '<< typeid (C).name () << endl;
}
template<typename A = int, typename B = double,typename C = string>
void hum (B b)
{
cout << typeid (A).name () << ' '<< typeid (B).name () << ' '<< typeid (C).name () << endl;
}
int main (void) 
{
foo<char, short, long> (); // c s l
foo<char, short> (); // c s Ss
foo<char> (); // c d Ss
foo<> (); // i d Ss
foo (); // i d Ss
bar<char, short, long> (100); // c s l
bar<char, short> (100); // c s Ss
bar<char> (100); // c i Ss -+
bar<> (100); // i i Ss +-> 隐式推断B=int
bar (100); // i i Ss -+
hum (100); // i i Ss ---> 隐式推断B=int
return 0;
}

 

3.连续出现的右尖括号不会再被误以为是右移运算符,可以使用小括号

#include <iostream>
#include <typeinfo>
using namespace std;
template<typename T>
void ptype (void) {
cout << typeid (T).name () << endl;
}
template<typename T> class Dummy {};
template<int x>
int square (void) {
return x * x;
}
int main (void) {
ptype<Dummy<int>> ();
cout << square<3> () << endl;
cout << square<(6>>1)> () << endl;//6/2=3
return 0;
}

 

this指针指向的是调用该函数的对象,那么*this就是调用该函数的对象本身

posted @ 2018-03-29 10:02  Truman001  阅读(420)  评论(0编辑  收藏  举报