Using-declaration of an existing namespace type vs creating a type alias

余生长醉 提交于 2019-12-04 07:02:52

Is there any difference ?

A type alias for a name in a namespace can appear in a class

struct S { using mytype = mynamespace::mytype; };

while a using-declaration may not.

What are the pros and cons of each syntax ?

The previous point is a pretty big con if you are dealing with class scope.

Other than that the two approaches are pretty much similar. An alias is a new name that stands exactly for the type that is aliased. While a using declaration brings the existing name of the type into scope. If you use mytype for both, you won't notice a difference.

Which one is the most used/recommended ?

I doubt there's consensus on this. Use the one you have to when you have to (class scope), but stick to your team's style guide otherwise.

I discovered another difference between the two syntaxes : it is not possible to define a type alias with the same name as an existing namespace in the same scope.

namespace name1 {
    struct name2 {};
}

namespace name2 {
    struct name3 {};
}

//error: 'typedef struct name1::name2 name2' redeclared as different kind of symbol
/* typedef name1::name2 name2; */

//OK
using typename name1::name2;

//error: 'name2' does not name a type
/* name2 val1 = {}; */

//OK disambiguation with keyword "struct"
struct name2 val2 = {};

//OK namespace qualifier with "::"
name2::name3 val3 = {};

int main(){
    //OK different scope
    typedef name1::name2 name2;
    name2 val = {};
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!