C++11使用using定义别名(替代typedef)

5 篇文章 0 订阅

C++11使用using定义别名(替代typedef)
详细见例子:

#include <map>
#include <string>
#include <list>

int _callBack()
{
    printf("call back print\n");
    return 0;
}

template <typename T1,typename T2>
int _add(T1 t1,T2 t2)
{
    double var = t1+t2+0.5;
    return  static_cast<int>(var);
}

//函数指针重定义
using FP_Print = int (*)();

template <typename T1,typename T2>
using Fp_add = int (*)(T1 ,T2 );


//类型重定义
template <typename T>
using map_str_t = std::map<std::string,T>;

//自定义类型重定义
template <typename T>
struct MyAlloc
{
    MyAlloc(T t)
    {
        t *= 2;
        m_t = t;
    }
    T print()
    {
        return  m_t;
    }
    T m_t;

};
template<typename T>
using MAllocList = std::list< MyAlloc<T> >;

//任意类型转换
template <typename T>
using type_t = T;
template <typename T>
T print(type_t<T> t)
{
    return t;
}

int main()
{

    //类型重定义1
    {
        map_str_t<int>  num;
        num["abc"] = 100;
        num["def"] = 99;
        auto it = num.begin();
        while (it != num.end()) {
            printf("%s:%d\n",it->first.c_str(),it->second);
            it++;
        }
    }

    //类型重定义2
    {
        map_str_t< std::string >  trans;
        using ss = map_str_t<std::string>::value_type;
        trans.insert(ss("abc","ABC"));
        trans.insert(ss("def","def"));
        auto it = trans.begin();
        while (it != trans.end()) {
            printf("%s:%s\n",it->first.c_str(),it->second.c_str());
            it++;
        }
    }


    //函数指针重定义
    {
        FP_Print fp = _callBack;
        fp();

        Fp_add<int,double> f_add = _add;
        printf("1+1.99=%d\n", f_add(1,1.99));
    }

    //自定义类型重定义
    {
        MAllocList<int>  lst;

        for(int i = 0;i < 10;i++){
            lst.push_back(i);
        }

        MyAlloc<int> v(10);
        lst.push_back(v);

        auto var = lst.begin();
        while (var != lst.end() ) {
            printf("%d ",var->print());
            var++;
        }
    }

    //任意类型转换
    {
        type_t<unsigned int> i = 20;//等价unsigned int
        printf("%u\n",print(i));

        using LL = long long;
        LL _time = (60*60*24*365);
        printf("%lld\n",_time);
    }

    return 0;
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值