C++ 新特性using

#include <iostream>


/** using语法与typedef一样,并不会创建出新的类型,它们只是给
 *  某些类型定义新的别名,using相比较typedef优势在于定义函数指针别名时看起来
 *  更加直观,并且可以给模板定义别名
 */

template <typename T>
using myMap = std::map<int, T>;
void Test()
{
    myMap<int> map1;
    map1.insert(std::make_pair<int, int>(1, 2));
    map1.insert(std::make_pair<int, int>(1, 2));

    myMap<std::string> map2;
    map2.insert(std::make_pair<int, std::string>(1, "2"));
}

// 使用typedef模板类型,需要使用struct包裹下,using 相比简单些
template <typename T>
struct STMap
{
    typedef std::map<int, T> myMap;
};

void Test1()
{
    STMap<int>::myMap map1;
    map1.insert(std::make_pair<int, int>(1, 2));
    map1.insert(std::make_pair<int, int>(1, 2));

    myMap<std::string> map2;
    map2.insert(std::make_pair<int, std::string>(1, "2"));
}

// typedef 模板函数指针
template <typename T>
struct STFunc{
    typedef T(*type)(T, T);
};

int add(int l, int r) {
    return (l)+(r);
}

double add(double l, double r) {
    return (l)+(r);
}


void Test2(){

    STFunc<int>::type func1 = add;
    std::cout<<func1(1,2)<<std::endl;

    STFunc<double>::type func2 =  add;
    std::cout<<func2(1,2.1)<<std::endl;

}

// using 通过赋值语法来定义类型别名
template<typename T>
using funcType = T(*)(T,T); // using 

void Test3(){
    funcType<int> func1 = add; 
    std::cout<<func1(1,2)<<std::endl;

    funcType<double> func2 = add; 
    std::cout<<func2(1,2.1)<<std::endl;
}

// 2.using用在命名空间中,using namespace std; // 表明使用的是std命名空间中的函数,cout,map, stack

// 3.用在类中

// 4.用在类型别名
void Test4(){
	using int_t = int;
	int_t = 10;
}

// 5.定义函数指针
typedef int(*func)(int a, int b);
using func1=int(*)(int a, int b)
void Test5(){
	func fun_ptr_var1 = add(1,2);
	func1 fun_ptr_var2 = add(1,2);
}

int main() {
    Test1();
    Test2();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值