C++: using 关键字

文章目录

疑问

对于using,大家常说的功能,这里不要提,这里只是记录一下思考问题:
https://en.cppreference.com/w/cpp/language/type_alias
从这个网页看,功能是对类型起一个新的别名;其实这个功能可以由typedef 实现了,为什么还要做一个 using type=type1 呢?
增加了C程序员转型C++的一个障碍。
不是不愿意接收新事物,相当于有两套冗余的方式,需要我们来做记忆。
如果程序员一开始学的就是C++,也许就没有这种苦恼。

感觉using的作用已经overload了。

示例

using 的功能比typedef更松散,适用的范围更广,比如适用于template里的类型别名定义。如果使用typedef 会有问题。

[root@10 c++]# g++ template.cpp
template.cpp:9:1: error: template declaration of ‘typedeftypedef Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>
 ^~~~~~~
template.cpp:9:9: error: ‘Vec’ does not name a type; did you mean ‘getc’?
 typedef Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>
         ^~~
         getc
[root@10 c++]# more template.cpp
#include <iostream>
#include <vector>
using namespace std;

template<class T>
struct Alloc {
    
     };
template<class T>
//using Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>  这个没有问题
typedef Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>

int main()
{
    
    
        cout<<"abc"<<endl;
}

复杂示例

类型别名模板;
template<template<typename, typename…> class _Template, typename _Up,
typename _Tp, typename… _Types>
struct __replace_first_arg<_Template<_Tp, _Types…>, _Up>
{ using type = _Template<_Up, _Types…>; };

猜你喜欢

转载自blog.csdn.net/qq_36428903/article/details/125560778