Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A using-declaration can not be repeated in function scope. Why is that?

In [namespace.udecl]/10 you have the following example:

namespace A {
    int i;
}
namespace A1 {
    using A::i;
    using A::i; // OK: double declaration
}
void f() {
    using A::i;
    using A::i; // error: double declaration
}

This snippet compiles in clang.

like image 561
Belloc Avatar asked Jul 04 '15 14:07

Belloc


People also ask

What is the scope of using declaration?

Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce enumerators into namespaces, block, and class scopes (since C++20).

What is the use of using declaration in C++?

A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A .

Can a function be declared more than once?

Yes, you can declare (but not define) a function multiple times in a single translation unit. And yes, include guards usually prevent this, but that is not their only purpose.

What is declarative region?

A declarative region is a place where names can be declared in. I.e. they can be declared in a block, a class body, or in the bodies of a namespace, etc. A scope is just some snippet of program text.


1 Answers

The first is a declaration inside a namespace, and the multiple using statements could happen frequently using #includes. The second is inside a definition of a function, and you would never do that unless you made a mistake. You can't define the same symbol twice either, for example, but you can declare several times.

The using statement is also more than just a declaration. It is a bit stronger, as it imports a function from one namespace to another. For example, it can pull a protected base class member function into a derived class, making it public. It's almost a definition by linkage.

like image 176
Mark Lakata Avatar answered Oct 05 '22 00:10

Mark Lakata