Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the scope of the "using" declaration in C++?

Tags:

c++

I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).

using std::string; using std::vector;  class Foo { /*...*/ }; 

What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?

like image 342
Jeff Lake Avatar asked Oct 21 '08 18:10

Jeff Lake


People also ask

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 .

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 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

There's nothing special about header files that would keep the using declaration out. It's a simple text substitution before the compilation even starts.

You can limit a using declaration to a scope:

void myFunction() {    using namespace std; // only applies to the function's scope    vector<int> myVector; } 
like image 168
Eclipse Avatar answered Oct 19 '22 22:10

Eclipse