I usually use forward declaration predominantly, if I have a class that does not need complete definition in .hpp file
Ex)
//B.hpp
namespace A_file {
class A;
}
namespace B_file {
class B {
public:
B();
private:
A *ptr_to_A;
}
}
//B.cpp
#include "A.hpp"
using namespace A_file;
namespace B_file {
B(int value_) {
*ptr_to_A = new A(value_);
}
int some_func() {
ptr_to_A->some_func_in_A();
}
}
I write this kind of code. I think, it will save including the whole hpp again. (Feel free to comment, if you thing, this is not healthy)
Is there a way that I can do the same for objects/classes in std namespace?
If there is a way, is it okay or does it have side effects?
You can forward declare your own classes in header files to save compilation time. But you can't for classes in namespace std. According to the C++11 standard, 17.6.4.2.1:
The behavior of a C++ program is undefined if it adds declarations or
definitions to namespace std or to a namespace within namespace std
unless otherwise specified.
Note that some of these classes are typedefs of templated classes, so a simple forward declaration will not work. You can use #include<iosfwd> instead of #include<iostream> for example, but there are no similar headers with just forward declarations for string, vector, etc.
See GotW #34, Forward Declarations for more information.
Related
I remember being told that C++ classes have their own namespaces, and that the class name could be used as a namespace for scope resolution, like this:
// Example.h
class Example {
void Private();
public:
void Public();
}
and, later in a manner similar to this:
// Example.cpp
#include "Example.h"
using /*namespace*/ Example;
void Private() {}
void Public() {}
instead of:
// Example.cpp
#include "Example.h"
void Example::Private() {}
void Example::Public() {}
but I couldn't find neither an explanation nor an example of that in my books. A brief Google search was also a dead-end. Is this a real thing?
No, namespaces and classes are different.
However, namespaces and classes both introduce a scope which may be referred to using the scope resolution operator :: .
The using namespace N; declaration can only apply to namespaces. It's not possible to do something similar for a class. You can only do using Example::x; for specific names x inside Example to import them one by one.
When providing the member function body out-of-line, you must write Example::Private(), there is no alternative.
Yes, Every class has its own namespace that everything part of the class declaration belongs to.
You may employ the using directive as you indicate as explained here.
It should be noted that you cannot declare a namespace with the same name as a class as shown here:
namespace fubar
{
class snafu
{
...
};
}
// Cannot do stuff below (ERROR)
namespace fubar::snafu;
{
// this is not valid, once a class always a class
// once a namespace, always a namespace
// a class makes a namespace also but never JUST a namespace
}
Do be careful though. 'Using' too much can play real tricks on you and those who inherit your code.
I am trying to avoid including an auto-generated header (outside of my control), from inside my own headers. I therefore need to forward-declare a type Type that lives inside a namespace nm, which itself lives in the global namespace. Here is an example of MyHeader.h:
// My project defines two levels of nested namespaces
namespace foo { namespace bar {
namespace nm { struct Type; }
...
} }
Unfortunately this defines the new namespace foo::bar::nm and forward-declares the type foo::bar::nm::Type, which is not what I want. Ideally I would be able to forward-declare a type in the qualified namespace ::nm like this:
namespace foo { namespace bar {
namespace ::nm { struct Type; }
...
} }
My compiler complains I cannot use a qualified namespace here (using Intel ICC15 with C++11 settings). This forces me to put all such forward declarations at the beginning:
namespace nm { struct Type; }
namespace foo { namespace bar {
...
} }
In my case, this is inconvenient because I need to forward-declare many types and would prefer to do so alongside definitions of my own in various scattered places in my header. A workaround could be to constantly be "closing" and "re-opening" my nested namespace, which is not ideal.
Why can't I forward-declare a type in a qualified namespace ?
Because the C++ standard says so.
There is no real reason I know of. This is just not supported, probably, no one needed it and no one ever requested it. I see the benefit in your particular case, but since the forward declarations are expected to be provided in a separate file, you'd be better off by simply creating your own *_fwd.h with all the forward declarations inside it in the single namespace.
You can't because it's ambiguous. If you wrote:
extern int foo::bar;
Are you forward declaring an int named bar in namespace foo, or are you forward declaring an int named bar inside the class foo? There's no way for the compiler to know.
In a C++ implementation file, I have the option to write something like:
name::space::ClassName::someFunction(int param) {
// impl
}
instead of
namespace name {
namespace space {
ClassName::someFunction(int param) {
// impl
}
}
}
which I find very convenient and more readable. Can this somehow be used in header files, too? Something like this:
class name::space::ClassName {
// declarations
};
instead of
namespace name {
namespace space {
class ClassName {
// declarations
};
}
}
If something like this is possible, then under which conditions? I could imagine, that one would need to forward declare the namespace forward declare the classes within the namespace like this:
namespace name {
namespace space {
class ClassName;
}
}
before being able to use this:
class name::space::ClassName {
// declarations
};
in a header file.
But somehow I am not able to get this to work 1]. Is it even possible? What bothers me is, that with nested namespaces I have to indent 2 tabs until I can actually declare my class. I would like to use that space in my header files, but I don't want to omit the tabs since this would be against the "everything in curly brackets needs to be tabbed once"-rule (I don't know if there is an actual name for this. If there is, excuse my ignorance, I don't know any :S
1] The problem I faced was not related to the question. The approach actually works, but it has drawbacks (see accepted answer).
If you simply don't want the namespace braces enveloping your class definition, you can certainly achieve that by defining the namespace somewhere else with just the class declaration inside. That way, you can come up with something like this:
#ifndef MYCLASS_H
#define MYCLASS_H
namespace ClassNamespace { class MyClass; };
class ClassNamespace::MyClass
{
public:
MyClass();
~MyClass();
void a();
private:
};
#endif // MYCLASS_H
for the header and this:
#include "MyClass.h"
#include <iostream>
using namespace std;
ClassNamespace::MyClass::MyClass()
{
}
ClassNamespace::MyClass::~MyClass()
{
}
void ClassNamespace::MyClass::a()
{
cout << "hello";
}
for the implementation.
As you can see, the namespace doesn't enclose the class definition, just its declaration.
As a final note, I personally don't know why you'd want to do this or think it looks nicer to read. I'd personally much rather see the namespace encapsulate the class definition as well as the function definitions. But maybe I've been the odd one all along...
No, it doesn't work. One problem is that with
namespace name {
namespace space {
class ClassName {
// declarations
}
}
}
you can tell that it is two namespaces and one class.
However, with
class name::space::ClassName {
// declarations
}
you cannot tell if space is a namespace or a class containing a nested ClassName.
What you can do is save on your tabbing. It is possible to write
namespace name { namespace space {
class ClassName {
// declarations
}
}}
What you are seeking does not work.
One explanation is that all C++ class and struct types are implicitly associated with their own namespace (which has the same name as the class).
So, given
class name::space::ClassName
{
// declarations
};
the compiler has no way to determine whether name and space are actually namespaces or classes (at best, it must conclude that the construct is ambiguous). So the compiler needs to be explicitly told that name is a namespace, that space is a namespace within name, before being told that ClassName is a class within them.
Hence the need for
namespace name
{
namespace space
{
class ClassName;
}
}
to forward specify both namespaces and forward declare ClassName within them.
No, it is not possible. The only way to define a namespace is using the namespace keyword in combination with curly braces.
7.3.1 Namespace definition [namespace.def]
1 The grammar for a namespace-definition is
namespace-name:
original-namespace-name
namespace-alias
original-namespace-name:
identifier
namespace-definition:
named-namespace-definition
unnamed-namespace-definition
named-namespace-definition:
original-namespace-definition
extension-namespace-definition
original-namespace-definition:
inlineopt namespace identifier { namespace-body }
extension-namespace-definition:
inlineopt namespace original-namespace-name { namespace-body }
unnamed-namespace-definition:
inlineopt namespace { namespace-body }
namespace-body:
declaration-seqopt
You can define namespace's members outside the namespace, although it must have been declared inside the namespace (emphasis mine):
7.3.1.2 Namespace member definitions [namespace.memdef]
2 Members of a named namespace can also be defined outside that namespace by explicit qualification (3.4.3.2)
of the name being defined, provided that the entity being defined was already declared in the namespace
and the definition appears after the point of declaration in a namespace that encloses the declaration’s
namespace.
When you write
namespace name {
namespace space {
class ClassName;
}
}
you are not declaring a class ClassName into the namespace space, you are just providing a forward declaration.
I write some header file. I want separately declare the namespaces hierarchy (for clarity), and and then declare functions and classes. For me it looks as a table of contents in the document. It would be very convenient for me: to see the full hierarchy of namespaces in one place. I write this:
// Namespaces hierarchy:
namespace Bushman{
namespace CAD_Calligraphy{}
//...
}
// Declarations of classes and functions
class Bushman::CAD_Calligraphy::Shp_ostream{
public:
explicit Shp_ostream(std::ostream& ost);
};
But MS Visual Studio shouts on such way of creation of the header file. I should write so:
namespace Bushman{
namespace CAD_Calligraphy{
class Shp_istream{
public:
explicit Shp_istream(std::istream& ist);
};
}
}
Why the first variant doesn't work? Is this restriction of the C++, or IDE?
P.S. My additional question is here.
Thank you.
The restriction is in §9/1: "If a class-head-name contains
a nested-name-specifier, the class-specifier shall refer to
a class that was previously declared directly in the class or
namespace to which the nested-name-specifier refers[...]". In
other words, the first appearance of the class name cannot be in
something like Bushman::CAD_Calligraphy::Shp_ostream.
What you can do is add forward declarations in your initial
declaration of the hierarchy:
// Namespaces hierarchy:
namespace Bushman{
namespace CAD_Calligraphy{
class Shp_ostream;
//...
}
//...
}
// Declarations of classes and functions
class Bushman::CAD_Calligraphy::Shp_ostream{
public:
explicit Shp_ostream(std::ostream& ost);
};
Depending on how your headers are organized, this might even be
better from the human point of view: your header starts with
a sort of index of what is defined in it.
To quote the standard: Section 7.3.1.2 point 2:
Members of a named namespace can also be defined outside that
namespace by explicit qualification (3.4.3.2) of the name being
defined, provided that the entity being defined was already declared
in the namespace and the definition appears after the point of
declaration in a namespace that encloses the declaration’s namespace.
namespace Q {
namespace V
void f();
}
void V::f() { /∗ ... ∗/ } // ok.
void V::g() { /∗ ... ∗/ } // Error: g() is not yet a member of V
namespace V
void g();
}
}
namespace R {
void Q::V::g() { /∗ ... ∗/ } // // error: R doesn’t enclose Q
}
So, you could do what you have in your original post, if you declare the class name there:
namespace Bushman{
namespace CAD_Calligraphy {
class Shp_ostream;
...
}
}
That's how C++ works.
It's consistent with other nested declarations: you can't add members to a class from outside the class:
class A
{
};
void A::f() { } // Error!
And you can't add enumerators to an enum from outside:
enum E { E1 = 1, E2 = 2 };
E::E3 = 3; // Error!
You need to "open" the scope and declare the entity inside the scope. Once it's declared you can define it outside that scope, using a nested-name:
class A
{
void f(); // declare
};
void A::f() { } // define
First of all, C++ is not designed to work like that. So it is not a surprise that this is happening.
But, since you're using Visual Studio, you could take advantage of partial classes. Unfortunately, it seems this characteristic is only related to C++/CX so maybe yo won't be able to use it.
You will still need to declare a partial class in your namespace hierarchy, but I guess it could be empty.
To be honest, I haven't used this feature and I don't know how far can it be bent in order to achieve what you want. But you could anyway give it a try.
Remember that this is a Visual Studio extension, so your code won't be cross-platform.
Hope this helps. Somehow.
Like :
using ::size_t; using ::fpos_t; using ::FILE;
In fact it's a question inspired by the comment under this question:
When is .h not needed to include a header file?
This is called using declaration. There are actually two ways you can use the using keyword. There is a third special form of using declarations used inside class definitions, but i'll focus on the general using declaration here. (see below).
using declaration
using directive
These have two very different effects. A using declaration declares a name to be an alias to another declaration or a set of declarations (if you were to name a set of overloaded functions). The name is declared in the current scope. That is, you can use it inside blocks too
int main() {
using std::swap;
// ...
}
This is quite useful if you use a name very often locally and you don't want to prefix it in all uses, and it's also useful in implementing the swap using argment dependent lookup idiom.
A using directive names a namespace and does not declare any names. Instead it will modify name lookup to find names that aren't really declared where it thinks they are. For unqualified name lookup, it find names declared in the enclosing namespace that encloses both the using directive and the target namespace. All names that are declared in the target namespaces will be found:
int cout;
int main() {
using namespace std;
// cout << 1; ambiguous!
}
Here, cout will be thought as being declared twice in the global namespace, and causes an ambiguity (:: encloses both main and std). In qualified namelookup, it will build the transitive closure of a namespace with all the namespaces named in using directives.
using namespace foo;
int main() {
::c++;
}
c is not only looked up in the global namespace, but also in the namespace foo and in the namespaces that foo has using directives for and so on. If however the global namespace would contain a direct declaration (including a using declaration), that declaration will hide the declarations found indirectly by using directives:
using namespace foo;
int c;
int main() {
::c++; // not ambiguous!
}
Using declarations can appear in many places, including inside class definitions. Its meaning is similar to its meaning otherwhere with an important restriction: It declares a name to be an alias to one or more declarations, but the declarations must be members of a base class. This is very useful for making names visible in a derived class that would otherwise be hidden by the same name declared there
struct base {
void f();
};
struct derived : base {
using base::f; // name "f" declared in derived
void f(int); // overloads the using declaration
};
Now you can call d.f(). If there were no using declaration, then name lookup would only find one declaration of f in derived and stop lookup, not delving into the base class scope:
derived d;
d.f(); // invalid without the using declaration
d.f(0); // valid with or without the using declaration
// explicitly starting lookup in base: valid with or without the using declaration
d.base::f();
It also allows to change the accessibility of base-class members, although you should use that sparingly :)
In practice, i found it useful for making virtual member function re-visible:
struct base {
virtual void f();
virtual void f(int);
};
struct derived : base {
// using base::f; would solve it
virtual void f() { ... }
};
Oops - now d.f(0); is invalid because name lookup only finds the zero parameter f! The using directive would solve it. Notice that if you alias a function declaration that has the same parameter types and constness as an explicit declaration (like f() in this case), then the explicit declaration will still hide the one that the using declaration is an alias for - so both f() functions won't conflict in this case.
An alternative to solve this is using the non-virtual interface idiom
struct base {
void f() { do_f(); }
void f(int) { do_f(0); }
private:
virtual void do_f();
virtual void do_f(int);
};
struct derived : base {
private:
virtual void do_f() { ... }
};
struct derived1 : derived {
private:
virtual void do_f(int) { ... }
};
Now, both d.f(0) and d.f() are valid no matter on what object you call it.
Unfortunately the example you're looking at is obscure.
using ::_Filet;
As others have noted, the using declaration makes a name from the specified namespace available in the current namespace. In that file there appear to be no namespaces opened, so you'd assume the current namespace is the global namespace, and also the :: with nothing before it addresses the global namespace. So here we seem to be moving a name from the global namespace into the global namespace. What's up with that?
The answer is in the use of a macro:
_STD_BEGIN
This is defined as namespace std {. So what the using declarations are doing is making those names appear in the std namespace, where otherwise they would only be in the global namespace.
using <some symbol> pull a symbol from its namespace into the current namespace. Assume the following code:
namespace foo {
// Assume you want to use std::string, you can either do
std::string bar;
// or
using std::string;
string bar;
}
As you can see, you can either qualify the symbol using its namespace (first line of code) or the second way. For symbols you use quite often, pulling them into the namespace tends to make the code a little more readable but if you have a conflict (say, foo contains a string class of its own which is bad practise but might happen), qualifying it with the appropriate namespace will allow you to resolve the conflict.
The namespace :: is a special case as it refers to the global namespace; in this particular case, the functions you're referring to are C functions and C doesn't know about C++ namespaces, so they end up in the global namespace.
Namespaces in C++ are a very powerful mechanism to avoid symbol naming clashes and I'd strongly encourage any C++ programmer to use them.
The 'using' keyword allows you to bring names from a namespace into the current namespace.
If you would like to use a name inside a namespace without bringing them into your current namespace, you would have to use the <namespace name>::<name> format, as in the following:
std::cout << "Hello World";
If cout is brought into the current namespace, then you can use it like below:
cout << "Hello World";
The using keyword can be used the following ways:
As a using directive (using namespace <namespace name>;):
using namespace std;
This brings all names inside the std namespace into the current namespace.
As a using declaration (using <namespace>::<member name>;):
using std::cout;
This brings only the std::cout name into the current namespace.
using makes a name from the specified namespace available in the current namespace.