C++11新特性之模板的改进

C++11关于模板有一些细节的改进:

  • 模板的右尖括号
  • 模板的别名
  • 函数模板的默认模板参数

模板的右尖括号

C++11之前是不允许两个右尖括号出现的,会被认为是右移操作符,所以需要中间加个空格进行分割,避免发生编译错误。

int main() {
    std::vector<std::vector<int>> a; // error
    std::vector<std::vector<int> > b; // ok
}

模板的别名

C++11引入了using,可以轻松的定义别名,而不是使用繁琐的typedef

typedef std::vector<std::vector<int>> vvi; // before c++11
using vvi = std::vector<std::vector<int>>; // c++11
template<class T>
struct Alloc { };
template<class T>
using Vec = vector<T, Alloc<T>>; // 类型标识为 vector<T, Alloc<T>>
Vec<int> v; // Vec<int> 同 vector<int, Alloc<int>>

使用using明显简洁并且易读,大家可能之前也见过使用typedef定义函数指针之类的操作,那烂代码我就不列出来了,反正我是看不懂也不想看…以后都可以使用using,额还是列出来吧。

typedef void (*func)(int, int); // 啥玩意,看不懂
using func = void (*)(int, int); // 起码比 typedef 容易看的懂吧

上面的代码使用using起码比typedef容易看的懂一些吧,但是我还是看不懂,因为我从来不用这种来表示函数指针,用std::function()、std::bind()、std::placeholder()、lambda表达式它不香吗。

函数模板的默认模板参数

C++11之前只有类模板支持默认模板参数,函数模板是不支持默认模板参数的,C++11后都支持。

template <typename T, typename U=int>
class A {
    T value;
};

template <typename T=int, typename U> // error
class A {
    T value;
};

类模板的默认模板参数必须从右往左定义,而函数模板则没有这个限制。

template <typename R, typename U=int>
R func1(U val) {
    return val;
}

template <typename R=int, typename U>
R func2(U val) {
    return val;
}

int main() {
    cout << func1<int, double>(99.9) << endl; // 99
    cout << func1<double, double>(99.9) << endl; // 99.9
    cout << func1<double>(99.9) << endl; // 99.9
    cout << func1<int>(99.9) << endl; // 99
    cout << func2<int, double>(99.9) << endl; // 99
    cout << func1<double, double>(99.9) << endl; // 99.9
    cout << func2<double>(99.9) << endl; // 99.9
    cout << func2<int>(99.9) << endl; // 99
    return 0;
}

对于函数模板,参数的填充顺序是从左到右的。

同时C++11支持变长参数模板:

template <typename T>
void func(const T& t){
    cout << t << '\n';
}

template <typename T, typename ... Args>
void func(const T& t, Args ... args){
    cout << t << ',';
    func(args...);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

川峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值