[1 使用C++11让程序更简洁] 1.2 模板的细节改进(using别名)

1.2.2 模板的别名

typedef重定义类型:

typedef unsigned int uint_t

但它有一些限制,例如,定义一个模板很丑陋:

typedef std::map<std::string, int> map_int_t;
typedef std::map<std::string, std::string> map_str_t;
// 我们需要一个key为std::string的map模板,用typedef写法如下
template <typename Val>
struct str_map
{
    typedef std::map<std::string, Val> type;
};
 
str_map<int>::type map1;

代码很烦琐。使用C++11 using别名语法修改如下,简洁了很多。

template <typename Val>
using str_map_t = std::map<std::string, Val>;
 
str_map_t<int> map;

使用场景:

1 定义普通类型别名

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>;

2 定义语法别名

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

3 定义模板别名

template <typename T>
struct func_t
{
    typedef void (*type)(T, T);
};
// 使用func_t模板
func_t<int>::type x1;
 
template <typename T>
using func_t = void (*type)(T, T);
// 使用func_t模板
func_t<int> x2;

1.2.3 函数模板的默认模板参数

C++03类模板支持默认参数,函数模板不支持默认参数

template <typename T, typename U = int, U N = 0>
struct Foo
{
    //...
};
// error
template <typename T = int>
void func(void)
{
    //...
}

C++11后函数模板也支持了默认参数。

注意,函数模板的默认填充顺序是从左向右的:

template <typename R = int, typename U>
R func(U val)
{
    // val
}
 
int main()
{
    func<long>(123);
    return 0;
}

函数模板的返回值类型为long,不是int。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值