Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is not a question about the difference between using and typedef for creating type aliases. I would like to provide access to an existing type from a namespace inside a code block or a function.

I found two different ways :

I can "include" the type with a using declaration :

using typename mynamespace::mytype;

Or I can create a type alias :

typedef mynamespace::mytype mytype;
using mytype = mynamespace::mytype; //C++11
  1. Is there any difference ?
  2. What are the pros and cons of each syntax ?
  3. Which one is the most used/recommended ?

Thank you.

Related question : Using-declaration of an existing type from base class vs creating a type alias inside child class

like image 309
Baptistou Avatar asked Oct 18 '19 09:10

Baptistou


People also ask

Can we create alias of a namespace?

You can also create an alias for a namespace or a type with a using alias directive.

What are is difference between using namespace directive and using the using declaration for accessing namespace members?

using directives Use a using directive in an implementation file (i.e. *. cpp) if you are using several different identifiers in a namespace; if you are just using one or two identifiers, then consider a using declaration to only bring those identifiers into scope and not all the identifiers in the namespace.

What is namespace alias?

namespace alias definition Namespace aliases allow the programmer to define an alternate name for a namespace. They are commonly used as a convenient shortcut for long or deeply-nested namespaces.

What is alias declaration in C++?

You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.


1 Answers

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.

like image 182
StoryTeller - Unslander Monica Avatar answered Oct 14 '22 21:10

StoryTeller - Unslander Monica