Scope of DataType declared in Namespace - c++

Sample.h
namespace Testing
{
enum Type
{
DATA = 0,
MORE_DATA
};
}
Now in Sample2.h, using the same namespace, can I access the DataType defined in Sample.h, without including it?
namespace Testing
{
Type test;
}
The question has come up, because I have files that implement this, and seem to build with no problem.
Another user is trying to build, but reports that he has to #include "Sample.h" in Sample2.h in order to build.

Most likely the files build because some earlier include file is including Sample.h for you. When the earlier include file is omitted (or moved after Sample2.h) the files will no longer compile.

Forward enum declarations are not supported in most current compilers. It is a planned feature of up coming C++0x. You can create pointers to Type probably, but cannot instantiate, this is compatible with other types (structs and classes) as well.
Ow, my bad, I saw it wrong i guess. Anyway, read the others and read this as well. Headers are not compiled stand alone. Therefore, if you don't include a required heading in your header and included that in the cpp file you will not run into any errors. As long as all the cpp files contain both headers with the required order there will be no problems at all. However, this is not a good idea, it is best to include any necessary files within your header and use header guards to ensure they are not added twice. I hope this makes sense.

Yes, you will need to include Sample.h within Sample2.h. The definition of Type is not visible to the compiler within Sample2.h simply because the namespace name is the same within the 2 files.
The only thing you gain by having the same namespace names in the 2 files is that Type does not need to have its namespace stated explicitly in Sample2.h. For instance, if the 2 namespaces were not the same:
Sample.h
namespace Testing
{
enum Type
{
DATA = 0,
MORE_DATA
};
}
Sample2.h
#include "Sample.h"
namespace Testing1
{
Testing::Type test;
}

Related

#includes within a namespace, to "embed" prewritten stuff in namespace

BRIEF: is it ever safe to do
namespace Foo {
#include "bar"
}
Before you blithely say no, I think I have some rules that allow it fairly safely.
But I don't like them, since they require the includer to separately include all global scope headers needed. Although this mightr be tolerable, if we imagine including within a namespace to be just a special management feature.
And overall, externs and forward declarations just don't work well from within namespaces.
So I gues I am asking
a) What other gotchas
b) is there a better way
== A [[Header-only library]] ==
I like writing libraries. [[Header-only libraries and linker libraries]].
E.g.
#include "Valid.hpp"
defines a template Valid, for a simple wrapper type.
(Don't get bogged down in "You should use some standard library for this rather than your own. This is an exanple. I dunno if Boost or C++ have yet standardized this. I have been using wrappers since templates were added to C++.)
Also, let us say, it is a header only library, that defines, in Valid.hpp,
a print function
std::string to_string( const Valid& v ) {
std::ostringstream oss;
if( v.valid() ) { oss << v; }
else { "invalid"; }
return oss.str();
}
And because I think it is the right thing to do,
I have Valid.hpp include the headers it depends on:
Valid.hpp:
#include <iostream>
#include <sstream>
template<typename T>
class Valid {
private:
T value_;
bool valid_
...
};
...
std::string to_string( const Valid<T>& v ) { ...
So far, so good.
I can use Valid straightforwardly.
== Name collision - trying to use include within namespace to work around ==
But sometimes there is a collision.
Sometimes somebody else has their own Valid.
Namespaces to the rescue, right? But I don't want to change all of my existing code to use the namespace.
So, I am tempted, in a new project that has a collision, to do
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
PROBLEM: the headers included are no longer freestanding. Everything defined inside is no placed inside
namespace AG::Wrapper.
It's not hard to "fix".
Al we "must" do is include all the top level libraries that Valid.hpp depends on.
If they have include guards, they will not be re-included.
#include <iostream>
#include <sstream>
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
But it is no longer freestanding. :-(
Worse, sometimes the header-only library contains extern declarations and forward declarations of stuff outside itself.
These declarations get placed inside the namespace too.
In particular, if the extern declarayion is inside a function defined in the namespace.
I.e. sometimes we use extern and forward declarations, rather than included an entire header file.
These get included in the namespace.
Q: is there a better way?
== :: doesn't do it ==
Hint: :: doesn't do it. At least not all the time, not in gcc 4.7.2.
(Gcc's behavior in this has changed over time. Gcc 4.1.2 behaved differently.)
E.g.
Type var;
namespace Foo {
void bar() {
extern ::Type ::var;;
extern ::Type ::Foo::bar;
extern ::Type::foo ::bar; // see the ambiguity?
};
But it's not just the ambiguity.
int var;
namespace Foo {
void bar() {
extern int var;
};
works - Foo::bar'svar is equal to ::var.
But it only works because of the declaration outside the namespace.
The following doesn't work
header
int var;
cpp
namespace Foo {
void bar() {
extern int var;
}
}
although the following does:
header
int var;
cpp
void bar() {
extern int var;
}
}
Basically, what this amounts to saying is that
it is not a trivial refactoring to put functions inside a namespace.
Wrapping a namespace around a chunk of code,
whether or not it is #include'd,
is not a sufficient.
... at least not if there are extern or forward declarations.
And even if you
== Opinion against putting includes within namespaces ==
Stackoverflow folks seem to be against putting #includes inside namespaces:
E.g. How to use class defined in a separate header within a namespace:
... you should never write a #include inside a namespace. Where "never" means, "unless you're doing something really obscure that I haven't thought of and that justifies it". You want to be able to look at a file, and see what the fully-qualified names are of all the things in it. You can't do that if someone comes along later and sticks an extra namespace on the front by including from inside their namespace. – Steve Jessop Jan 6 '12 at 16:38
Overall question:
Is there any way, from deep within a namespace,
to say "and now here are some names that I am depending on from the outside world, not within the namespace."?
I.e. I would like to be able to say
namespace A {
void foo() {
// --- here is a reference to gloal scope extreren ...
I know this is an old question, but I want to give a more detailed answer anyway. Also, give a real answer to the underlying problem.
Here's just a few things that can go wrong if you include a header from within a namespace.
The header includes other headers, which are then also included from within the namespace. Then a different place also wants to include these headers, but from outside the namespace. Because the headers have include guards, only one of the includes actually goes in effect, and the actual namespace of the stuff defined in the headers suddenly subtly depends on the order you include other headers.
The header, or any of its included headers, expects to be in the global namespace. For example, standard library headers will very often (in order to avoid conflicts) refer to other standard stuff (or implementation details) as ::std::other_stuff, i.e. expect std to be directly in the global namespace. If you include the header from within a namespace, that's no longer the case. The name lookup for this stuff will fail and the header will no longer compile. And it's not just standard headers; I'm sure there are some instances of this e.g. in the Boost headers too.
If you take care of the first problem by ensuring that all other headers are included first, and the second problem by making sure no fully qualified names are used, things can still go wrong. Some libraries require that other libraries specialize their stuff. For example, a library might want to specialize std::swap, std::hash or std::less for its own type. (You can overload std::swap instead, but you can't do that for std::hash and std::less.) The way to do this is close your library-specific namespace, open namespace std, and put the specialization there. Except if the header of the library is included in arbitrarily deeply nested namespaces, it cannot close those namespaces. The namespace std it attempts to open won't be ::std, but ::YourStuff::std, which probably doesn't contain any primary template to specialize, and even if it did, that would still be the wrong thing to do.
Finally, things in a namespace simply have different names than things outside. If your library isn't header-only but has a compiled part, the compiled part probably didn't nest everything in the namespace, so the stuff in the library has different names than the stuff you just included. In other words, your program will fail to link.
So in theory, you can design headers that work when included within a namespace, but they're annoying to use (have to bubble up all dependencies to the includer) and very restricted (can't use fully qualified names or specialize stuff in another library's namespace, must be header-only). So don't do it.
But you have an old library that doesn't use namespaces, and you want to update it to use them without breaking all your old code. Here's what you should do:
First, you add a subdirectory to your library's include directory. Call it "namespaced" or something like that. Next, move all the headers into that directory and wrap their contents in a namespace.
Then you add forwarding headers to the base directory. For each file in the library, you add a forwarder that looks like this:
#ifndef YOURLIB_LEGACY_THE_HEADER_H
#define YOURLIB_LEGACY_THE_HEADER_H
#include "namespaced/the_header.h"
using namespace yourlib;
#endif
Now the old code should just work the way it always did.
For new code, the trick is not to include "namespaced/the_header.h", but instead change the project settings so that the include directory points at the namespaced subdirectory instead of the library root. Then you can simply include "the_header.h" and get the namespaced version.
I don't think it's safe. You put all your includes into the namespace Foo...
Imagine some of your includes include something from the std namespace... I cannot imagine the mess !
I wouldn't do that.
Header files are not black boxes. You can always look at a header you're including in your project and see if it is safe to include it inside a namespace block. Or better yet, you can modify the header itself to add the namespace block. Even if the header is from a third-party library and changes in a subsequent release, the header you have in your project won't change.

C++ : Using typedefs across multiple files in a namespace.

I am defining a namespace across multiple files. In one file, within the namespace I have declared a type called MyType. In another file and still within the namespace, shouldn't I be able to see that type, without having to include a header file as well? Below is an example :
FILE A
namespace EE
{
typedef int MyType;
}
FILE B
namespace EE
{
MyType a = 10;
}
Again, to my understanding namespaces helped to clean up inclusion. If I define a type that 30 files will use, I shouldn't have to include the header in all of them if I am using a namespace, or so I thought.
Namespaces were introduced to fight the problem of the names collision. Pretty much that is it. When you compile one file, an object file is generated. Information from this object file is not enriching the knowledge of the compiler when it is compiling the next file. This means that that you need to include your typedef definition as part of some header fine into each C/C++ file. And it is not important if your typedef is part of the namespace or not.
Note that typedefs are exception to the "one definition rule". You can have several identical typedefs in one translation unit, like the following:
typedef int MyInt;
....
typedef int MyInt;
This will not cause a syntax error.
There is one exception to the rule of "not enriching the knowledge" for exported templates. But this applies only to templates and this feature is not supported by compilers. After deliberation it was even removed from the standard.

Issue with static functions, g++ says the class hasn't been declared

I am trying to compile this code, and g++ keeps telling me that 'TimeFinder' has not been declared
Header File
#ifndef _TIMEFINDER_H
#define _TIMEFINDER_H
#include <vector>
#include "timefinder.cpp"
using namespace std;
class TimeFinder
{
public:
static vector<int> time_from_name(string filename);
static int calc_seconds (vector <int> time);
};
#endif
CPP File
#include "timefinder.h"
using namespace std;
vector<int> TimeFinder::time_from_name(string filename)//Line 14
{
//Method Body
}
int TimeFinder::calc_seconds (vector <int> time1)//Line 37
{
//Method Body
}
Why is this going on? I looked at other examples online, and my code seems to match what works for other people...
Edit: The exact error messages are
timefinder.cpp:14: error: ‘TimeFinder’ has not been declared
timefinder.cpp:37: error: ‘TimeFinder’ has not been declared
Edit2: I'm sorry I'm not very good at this yet, but I would like to thank everyone for their suggestions. Hopefully my code quality will begin to improve because of them.
Do not do this:
#include "timefinder.cpp"
You are pulling your definitions into your header so they appear before their declarations.
There is a lot of other stuff wrong with your code - the use of static members in the first place, passing vectors and strings by value when they should be references, and placing using directives in header files, but removing that #include should fix the immediate problem.
#include "timefinder.cpp"
Header files usually don't include their .cpp implementation file but only whatever other .h file is required to satisfy the definitions required. Usually it's the other way around where .cpp files include the required .h files necessary to fulfill the dependencies.
using namespace std;
This can also cause a lot of havoc and should be avoided in header files. In header files you should always fully qualify your names with their namespace. The reason is if you import this header file into another one that defines the same symbol locally in their namespace like "cout" then both the std::cout and user::cout would clash and cause a compile error or even worse possibly pick the wrong definition and cause a linking error later.

Pulling C/C++ standard library into your project namespace, good idea?

I'm porting some open source code so that it can build on another c++ compiler. One of the difficulties and themes that seem to keep cropping up are implementation differences of the provided standard library by the compiler.
For example, one of the source files that I'm compiling includes <sys/types.h>. However, it gives me the following errors:
Error E2316 g:\Borland\BCC593\Include\sys/types.h 45: 'time_t' is not a member of 'std'
Error E2272 g:\Borland\BCC593\Include\sys/types.h 45: Identifier expected
After looking at the root cause of this I found that one of the main include headers of the project is including <sys/types.h> in this pattern:
project_source1.cpp:
#include "../TargetPlatform.h"
#include "project_config.h"
#include <windows.h>
namespace project_namespace {
#include "project_component/all.h"
// more project includes down here
// ...
}
project_component/all.h:
#ifndef INCLUDE_GUARDS
#define INCLUDE_GUARDS
#include <sys/types.h>
#include "project_header1.h"
#include "project_header2.h"
// and other headers etc..
// followed with class definitions and what not.
#endif
This is all well and good except for one problem, the <sys/types.h> is implemented something like this for the compiler I'm porting to:
<sys/types.h> trimmed to the essence:
namespace std {
typedef long time_t;
typedef short dev_t;
typedef short ino_t;
typedef short mode_t;
typedef short nlink_t;
typedef int uid_t;
typedef int gid_t;
typedef long off_t;
} // std
using std::time_t;
using std::dev_t;
using std::ino_t;
using std::mode_t;
using std::nlink_t;
using std::uid_t;
using std::gid_t;
using std::off_t;
And this is the cause of the compile error I'm seeing. Because the project is including <sys/types.h> inside its own namespace, things like time_t, off_t, dev_t etc get put into the scope project_namespace::std:: which is obviously not what's intended.
What's the best way to handle this? Keep in mind there could be other standard library headers defined in a similar fashion and not just sys/types.h. Are there any C++ idioms that's relevant or semi-related to this issue(or possibly even at odds with it due to the way this is implemented)? If so, how can it be reconciled?
Thanks
This is a bad idea. Do not do things this way. Put the namespace declarations inside each header file. Never have a #include directive inside the scope of a namespace.
Never is a strong word, and there are very rare cases in which you might want to do this. If the file you're #includeing also has #include directives, you almost certainly do not want to be doing this, even more so than if they didn't.
If you need to be able to easily rename your namespace or use the same header to declare the same symbols in several different namespaces depending on context, use the preprocessor to change the namespace name instead. That's extremely ugly to do, but much better than what you're currently doing.
One thing you can do as a quick and dirty solution to this is #include <sys/types.h> and any other system header that's included before the namespace declaration. This will cause the double-inclusion guards in the system header files to kick in and avoid declaring stuff inside the namespace.
I would say you need to change the offending code so that the standard types are no longer defined within project_namespace.
It seems to me you have two major issues: [1] you have a catch-all header in project_all.h and [2] it's #included inside namespace project_namespace. I'll address the latter first. If your project has things it wants to put in its own namespace, that's fine, but it should be done as follows:
// Foo.h
// includes go here
namespace project_namespace {
class Foo { ... }
}
// Foo.cpp
// includes go here
namespace project_namespace {
// Foo implementation goes here
}
... in other words, your classes' header and implementation files need to say what namespace the classes belong in, "self-namespacing" as it were. All your #includes are outside a namespace because the header file for each class declares the namespaces the class belongs to. This is the convention used by the standard library.
Now if you still want to use a project_all.h you can do so. Without the namespace -- because each header file will place its declarations in the namespace it wants to (or not).
But it would be better to dispense with project_all.h; instead, #include the header files individually and make the dependencies explicit. And if the response is "there are too many header files", that's probably a sign of a high degree of coupling between your components.
I realize this is probably not the answer you wanted, sorry ...

visibility problems with namespaces

I have two source files, one named main.cpp (where the namespace M is defined) and the file engines.h (where several names are defined).
main.cpp includes engines.h.
engines.h need to use the stuff inside M, and M needs to use the stuff inside engines.h.
I get an error doing using namespace M; in engines.h.
Don't use using namespace inside header files. This will get all the symbols from the namespace inside each translation unit that includes that header file, so you'll have a symbol mess (name conflict, which is probably what you're facing in your situation). Use full qualification inside the header files, or at least use the using namespace statement locally (inside a function or method where you what to improve readability).
For your situation, what is the error you get? What is the content of the headers?
You cannot do using namespace M before the namespace was defined. If there is a cyclic dependency, you need to solve it by using one or more techniques
Forward declare if your uses don't need to know the members or size of classes, but just handle with pointers or references to them:
namespace M { class MyCow; }
Define stuff in engines.cc
// engines.h
void f();
// engines.cpp
#include "main.h"
void f() { MyCow muuh; }
Use of the pimpl idiom reduces dependencies even more, as it keeps headers free of headers that are only used by implementations..
Split the part in .h files for the interface and .cpp files for the implementation to handle such dependencies. That way, headers are less dependent on other headers, and implementation files can include the headers.