What is "namespace clt and dmp"? - c++

I'm trying to implement a vector in c++.
Found this online: http://doingmyprogramming.com/2013/06/25/implementing-a-vector-in-c-working-smarter-not-harder/
I'm confused as to what namespace clt & namespace dmp are.
Thanks!

These are namespaces. In this case, they are structured this way:
global
-> clt
-> dmp
If you look few lines lower, you will see this code:
namespace clt {
namespace dmp {
template <typename T>
class vector {
..words..
};
}
}
It defines class vector<T> inside namespace dmp, which is itself defined inside namespace clt. So, when you are in global namespace (let's say, main() function), you must use explicit scope operator to be able to use vector. Example:
int main()
{
clt::dmp::vector<int> vecint; //Create vector of ints
//...
}
The most common example of a namespace is namespace std, which contains C++ standard library primitives.
Oh, and if you are concerned about their names (clt and dmp) - they are probably just abbreviations.

Related

Using functions from namespace inside other namespace

Is it any way to omit outer namespace name for some functions from other namespace inside top-level one?
void sample_func();
namespace foo {
void first_func();
namespace bar {
void second_func();
void sample_func();
}
Everything is trivial for first_func(): just typing using foo::first_func; allows to call it just as fist_func();
Everything is simple if I want to call second_func without any prefix: just using foo::bar::second_func; allows to call it as second_func();
But is there any way to call it as bar::second_func();? It will increase code readability - much better to type and see something like bar::sample_func instead of full foo::bar::sample_func without names confusion: obviously using namespace foo::bar is not an option in that case.
UPD I am not interested in importing the whole foo or bar namespace (i. e. using namespace ... directive! I need just some functions from them.
You can use
namespace bar = foo::bar;
to import foo::bar into current namespace as just bar.
Prefix it with the namespace:: or :: if not in a namespace i.e
::sample_func();
foo::first_func();
bar::second_func();
bar::sample_func();
You can use
using namespace foo;
in any declarative region where you wish to use just first_func() and bar::sample_func().
Example:
int main()
{
using namespace foo;
first_func();
bar::sample_func();
}

Is it ok to wrap code in anonymous namespaces for using directives? [duplicate]

This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.

Using Directive C++ Implementation

In C, if I use #include "someFile.h", the preprocessor does a textual import, meaning that the contents of someFile.h are "copy and pasted" onto the #include line. In C++, there is the using directive. Does this work in a similar way to the #include, ie: a textual import of the namespace?
using namespace std; // are the contents of std physically inserted on this line?
If this is not the case, then how is the using directive implemented`.
The using namespace X will simply tell the compiler "when looking to find a name, look in X as well as the current namespace". It does not "import" anything. There are a lot of different ways you could actually implement this in a compiler, but the effect is "all the symbols in X appear as if they are available in the current namespace".
Or put another way, it would appear as if the compiler adds X:: in front of symbols when searching for symbols (as well as searching for the name itself without namespace).
[It gets rather complicated, and I generally avoid it, if you have a symbol X::a and local value a, or you use using namespace Y as well, and there is a further symbol Y::a. I'm sure the C++ standard DOES say which is used, but it's VERY easy to confuse yourself and others by using such constructs.]
In general, I use explicit namespace qualifiers on "everything", so I rarely use using namespace ... at all in my own code.
No, it does not. It means that you can, from this line on, use classes and functions from std namespace without std:: prefix. It's not an alternative to #include. Sadly, #include is still here in C++.
Example:
#include <iostream>
int main() {
std::cout << "Hello "; // No `std::` would give compile error!
using namespace std;
cout << "world!\n"; // Now it's okay to use just `cout`.
return 0;
}
Nothing is "imported" into the file by a using directive. All it does is to provide shorter ways to write symbols that already exist in a namespace. For example, the following will generally not compile if it is the first two lines of a file:
#include <string>
static const string s("123");
The <string> header defines std::string, but string is not the same thing. You haven't defined string as a type, so this is an error.
The next code snippet (at the top of a different file) will compile, because when you write using namespace std, you are telling the compiler that string is an acceptable way to write std::string:
#include <string>
using namespace std;
static const string s("123");
But the following will not generally compile when it appears at the top of a file:
using namespace std;
static const string s("123");
and neither will this:
using namespace std;
static const std::string s("123");
That's because using namespace doesn't actually define any new symbols; it required some other code (such as the code found in the <string> header) to define those symbols.
By the way, many people will wisely tell you not to write using namespace std in any code. You can program very well in C++ without ever writing using namespace for any namespace. But that is the topic of another question that is answered at Why is "using namespace std" considered bad practice?
No, #include still works exactly the same in C++.
To understand using, you first need to understand namespaces. These are a way of avoiding the symbol conflicts which happen in large C projects, where it becomes hard to guarantee, for example, that two third-party libraries don't define functions with the same name. In principle everyone can choose a unique prefix, but I've encountered genuine problems with non-static C linker symbols in real projects (I'm looking at you, Oracle).
So, namespace allows you to group things, including whole libraries, including the standard library. It both avoids linker conflicts, and avoids ambiguity about which version of a function you're getting.
For example, let's create a geometry library:
// geo.hpp
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
and use some STL headers too:
// vector
template <typename T, typename Alloc = std::allocator<T>> vector;
// algorithm
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
But now, if we use all three headers in the same program, we have two types called vector, two functions called transform (ok, one function and a function template), and it's hard to be sure the compiler gets the right one each time. Further, it's hard to tell the compiler which we want if it can't guess.
So, we fix all our headers to put their symbols in namespaces:
// geo.hpp
namespace geo {
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
}
and use some STL headers too:
// vector
namespace std {
template <typename T, typename Alloc = std::allocator<T>> vector;
}
// algorithm
namespace std {
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
}
and our program can distinguish them easily:
#include "geo.hpp"
#include <algorithm>
#include <vector>
geo::vector origin = {0,0,0};
typedef std::vector<geo::vector> path;
void transform_path(geo::matrix const &m, path &p) {
std::transform(p.begin(), p.end(), p.begin(),
[&m](geo::vector &v) -> void { geo::transform(m,v); }
);
}
Now that you understand namespaces, you can also see that names can get pretty long. So, to save typing out the fully-qualified name everywhere, the using directive allows you to inject individual names, or a whole namespace, into the current scope.
For example, we could replace the lambda expression in transform_path like so:
#include <functional>
void transform_path(geo::matrix const &m, path &p) {
using std::transform; // one function
using namespace std::placeholders; // an entire (nested) namespace
transform(p.begin(), p.end(), p.begin(),
std::bind(geo::transform, m, _1));
// this ^ came from the
// placeholders namespace
// ^ note we don't have to qualify std::transform any more
}
and that only affects those symbols inside the scope of that function. If another function chooses to inject the geo::transform instead, we don't get the conflict back.

Can I undo the effect of "using namespace" in C++?

With using namespace I make the whole contents of that namespace directly visible without using the namespace qualifier. This can cause problems if using namespace occurs in widely used headers - we can unintendedly make two namespaces with identical classes names visible and the compiler will refuse to compile unless the class name is prepended with the namespace qualifier.
Can I undo using namespace so that the compiler forgets that it saw it previously?
No, but you can tell your coworkers that you should never have a using directive or declaration in a header.
As others said, you can't and the problem shouldn't be there in the first place.
The next-best thing you can do is bring in your needed symbols so that they are preferred by the name look-up:
namespace A { class C {}; }
namespace B { class C {}; }
using namespace A;
using namespace B;
namespace D {
using A::C; // fixes ambiguity
C c;
}
In some cases you can also wrap the offending includes with a namespace:
namespace offender {
# include "offender.h"
}
No, C++ Standard doesn't say anything about "undo". The best you are allowed to do is to limit scope of using:
#include <vector>
namespace Ximpl {
using namespace std;
vector<int> x;
}
vector<int> z; // error. should be std::vector<int>
But unfortunately using namespace Ximpl will bring all names from std namespace as well.
Not to my knowledge... But as a rule I only use "using namespace" in .cpp files.
The closest, that I'll try to use in header files is following:
//example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/**
* hating c++ for not having "undo" of using namespace xx
*/
#define string std::string
#define map std::map
class Example {
public:
Example (const char *filename);
Example (string filename);
~Example ();
private:
map<string,complicated_stuff*> my_complicated_map;
};
#undef string
#undef map
#endif //EXAMPLE_H_
after all, defines are #undef -able.
There are 2 problems:
1. it is ugly
2. separate #define and #undef for each name from the corresponding namespace are used
As stated you should not use using namespace sth in header files. When you need functionality from a namespace in your implementation you can leverage scopes like this:
void func() {
// some code agnostic to your namespace.
{
using namespace sth;
// some code aware of sth.
}
// some other code agnostic to your namespace.
}

using namespace issue

When I use the following
#include <map>
using namespace LCDControl;
Any reference to the std namespace ends up being associated with the LCDControl name space.
For instance:
Generic.h:249: error: 'map' is not a member of 'LCDControl::std'
How do I get around this? I didn't see anything specific to this on any documentation I looked over. Most of them said not to use: using namespace std;.
Here's line 249:
for(std::map<std::string,Widget *>::iterator w = widgets_.begin();
It looks like there's a std namespace within LCDControl that's hiding the global std namespace. Try using ::std::map instead of std::map.
I would say that either there's a using namespace std somewhere within the LCDControl namespace, or possibly there's an #include of a STL header that defines std within the LCDControl namespace.
e.g.:
namespace LCDControl
{
#include <map>
}
Which would define all the symbols in <map> as part of LCDControl::std, which in turn would hide the global std, or at least any symbols defined in the inner namespace, I'm not sure.
When I tried this under VS2008, I got an error:
namespace testns
{
int x = 1;
}
namespace hider
{
namespace testns
{
int x = 2;
}
}
int y = testns::x;
using namespace hider;
int z = testns::x; // <= error C2872: 'testns' : ambiguous symbol
The 'map' class lives in the std namespace, so you are going to have to qualify that somewhere. How are you qualifying your map object? You should have no problem doing this:
std::map<foo> myMap;
You can also do something like this if you do not want to explicitly qualify it every time, but also do not want to pollute your global namespace:
using std::map;