lorniper
lorniper

Reputation: 638

What's the purpose of declaring "namespace std {}"?

In some piece of code, I saw this declaration without understanding the exact meaning...

namespace std {};     // why?
using namespace std;

int main(){

...

}

Upvotes: 2

Views: 312

Answers (3)

andreee
andreee

Reputation: 4679

Contrary to the answers given above, I want to demonstrate a particular case where forward-declaring a namespace can be useful.

I make heavy use of Boost.Log in my application, where I use namespace lg = boost::log; for abbreviating long statements like boost::log::core::get()->.... The alias is declared in a general header file included by all components of my software, but I don't want to have all Boost.Log includes in this file, since not all components use logging. But in order to define the alias, I need to forward-declare boost::log. So my header file contains the following lines:

// boost::log namespace "forward" declaration
namespace boost { namespace log {}}
// Alternatively (from C++17 onwards):
namespace boost::log {}

// Namespace alias for boost::log.
namespace lg = boost::log;

That way, I don't need to define the lg alias in every file, which would be error-prone and tedious (and also I don't need to include the Boost.Log in the global header, which would possibly increase build times a lot).

If boost::log doesn't tell you much, think of other nested namespaces like std::chrono that one might want to alias.

Upvotes: 0

H. Guijt
H. Guijt

Reputation: 3375

That's a forward declaration of a namespace. You are not allowed to 'use' a namespace before it has been declared, so the declaration is necessary if you don't have any includes that bring in any part of 'std' beforehand.

Is it actually useful or necessary... That's doubtful. If you are including anything that brings in any part of std, you don't need the forward declaration. And if you are not, you don't need that using namespace std. So it might be a bit of boilerplate code - someone who was taught to 'always write using namespace std', and writes it even if it doesn't make any sense.

Upvotes: 3

Jesper Juhl
Jesper Juhl

Reputation: 31488

There is no point. I guess that code was written by someone who didn't really know what they were doing.

You'll get access to the namespace as soon as you include something anyway, so forward declaring it here doesn't really serve any purpose.

Upvotes: 2

Related Questions