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

    技术2022-07-12  90

    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; }
    Processed: 0.010, SQL: 9