您的位置:首页 > 编程语言 > C语言/C++

用C++11语法改进模版细节

2018-03-07 22:44 239 查看
1.模版右尖括号

2.模版别名

3.函数模版默认模板参数

1.模版右尖括号

早期的C++版本在模板中不支持连续的两个尖括号。Mingw中编译报错,vs中好像没发现这问题。如下代码

template <typename T>
struct Foo
{
typedef T type;
};

template<typename T>
class A {...};

Foo<A<int>>::type x; //error 编译出错 “>>”被当成操作符处理了,右移操作,二义性
Foo<A<int> >::type x; //ok 注意空格

//C++11编译器解决了上述问题,但也要注意与老版本不兼容的例子
template <int T> struct Foo {...};
Foo < 100 >> 2 > x;//err 二义性
Foo<(100 >> 2)> x;//ok


2.模版别名

从C++11开始可以用关键字using进行类型或模版别名声明

typedef unsigned int uint_t;
using uint_t = unsigned int;

typedef std::map<std::string, int> map_int_t;
using map_int_t = std::map<std::string, int>; //效果等价,语法不同,更简洁

typedef void(*pFunc)(int, int);
using pFunc = void(*)(int, int);

//C++98/03
//定义
template<typename T>
struct func_t
{
typedef void(*type)(T, T);
};
//使用
func_t::type xx_1;

//C++11
//定义
template <typename T>
using func_t = void(*)(T, T);
//使用
func_t<int> xx2;


3.函数模版默认模板参数

template<typename T = int>
void func(void) {}         //C++ 98/03 : err    C++11:ok

template<typename T>
struct identify
{
typedef T type;
};

template<typename T = int>
void func(typename identify<T>::type val, T = 0)
{
//...
}

int main(void)
{
func(1);       //T推导为int
func(1, 1.0);  //T推导为double
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: