Renaming namespaces - c++

I've been doing C++ for a long time now but I just faced a question this morning to which I couldn't give an answer: "Is it possible to create aliases for namespaces in C++ ?"
Let me give an example. Let's say I had the following header:
namespace old
{
class SomeClass {};
}
Which, for unspecified reasons had to become:
namespace _new
{
namespace nested
{
class SomeClass {}; // SomeClass hasn't changed
}
}
Now if I have an old code base which refers to SomeClass, I can quickly (and dirtily) "fix" the change by adding:
namespace old
{
typedef _new::nested::SomeClass SomeClass;
}
But is there a way to import everything from _new::nested into old without having to typedef explicitely every type ?
Something similar to Python import * from ....
Thank you.

using namespace new::nested;
Example at Ideone.
Or if you actually want a real alias:
namespace on = one::nested;
Example at Ideone.

This:
namespace old = newns::nested;
would seem to be what you want.

Related

what is "using" for? (in C++)

I recently have seen some codes for "using" and then I confused because of I don't know their syntax exactly.
1.
using callable_type = void(__stdcall*)(std::string);
auto Various_native::call_me(callable_type callable)
{
callable("--- from native ---");
}
using ST_CHAR = char;
using namespace System;
In the first two examples "using" plays a role similar to the older "typedef" keyword; it allows you to give a custom name/alias to an existing type, so that in latter code you can use that name (e.g. callable_type) instead of the original name (e.g. void(__stdcall*)(std::string)). That has the advantage of potentially making your code easier to read and/or write, and also the advantage that if you ever decide to change the code to use a different type instead, you only have to modify a single line of code rather than every piece of code that mentions the original type.
The third example (using namespace System;) tells the compiler to automatically look inside the System namespace for identifiers, if no namespace is explicitly specified. So for example if there is a function foo() that was declared inside the System namespace, code after the using namespace System; declaration can simply call foo() rather than having to spell out System::foo() every time.
Have a look at this: https://en.cppreference.com/w/cpp/keyword/using
Here are the ways to use using
/* clasic use: as an improved options to the c keyword typedef
for creating aliases for typenames in the local namespace */
using fullname = std::pair<std::string, std::string>;
using relavently_named_type = std::pair<std::pair<std::string, int>, float>;
fullname name{ "mark", "thompson" };
relavently_named_type variable_name{ { "text", 1 }, 1.0f };
/* importing named symbols to the local namespace */
using std::string, std::array, std::begin, std::end;
array character_array{ 'h','e','l','l','o',' ','w','o','r','l','d', };
string hello_world_string{ begin(character_array), end(character_array) };
std::cout << hello_world_string << '\n';
/* importing all names in a namespace into the local namespace */
using namespace std;
array character_array{ 'h','e','l','l','o',' ','w','o','r','l','d', };
string hello_world_string{ begin(character_array), end(character_array) };
std::cout << hello_world_string << '\n';
/* importing all names from an enum class/struct into the local namespace
(only since c++20) */
enum class material { wood, stone, iron, bronze, glass };
auto without_using = material::wood;
using enum material;
auto with_using = wood;
/* import to other visability from parent class(es) and/or
specify which version of "function" to use when refering to C::function */
class A
{
private:
int function();
};
class B
{
private:
int function();
};
class C : A, B
{
public:
using B::function;
};
Cppreference goes into far more detail but this covers the basic. Your question isn't phrased particulary well but i hope i gave the information you wanted. Generally if you're curios about language features and syntax you can find it on cppreference as long as you know the name. Especially look at their examples.

Prevent third party from using my entire namespace

Although I've searched, I don't know if this is possible at all.
How can I prevent a library user from writing using namespace myns; anywhere in his/her code?
Let's say I implemented a library that encloses all its elements in a namespace called myns:
namespace myns
{
class MyClass
{
};
class string
{
};
}
This library will be used by another programmer. How can I force him/her to use
// somewhere in code
myns::MyClass myClass;
myns::string myString;
std::string stdString;
instead of
using namespace myns;
// somewhere in code
MyClass myClass;
string myString; // this would most likely be a mess
string stdString;
This would help with namespace collisions.
You can't. The standard says one can write using namespace myns; to get all the names, and there is nothing you can do about that.
If the user gets collisions after using namespace XXX;, that's their own fault. Generally, it is not possible to stop people from shooting themselves in the foot if they try to.
In the end, pulling in all names from some third party namespace is not something that happens on accident, but has been discouraged since about the dawn of time. If the user decides to do it anyways, they better know what they are doing. Really not the problem of the library maintainer.
One (questionable) workaround I can think of is replacing your namespace with a class or a struct of the same name and turning everything in your namespace into a (static) member of this class.
struct myns final
{
class MyClass
{
}
class string
{
}
private:
// private constructor, copy constructor and assignment operator
// ...
};
This would preclude programmers, using your library from writing using namespace myns but... well, like I said, I consider such a workaround to be quite questionable.
Note that users will still be able to use type aliases, such as:
using string = myns::string;

How can I stop letting other clutter / expand my namespace?

Suppose, if I have a namespace in one header file. I don't want that people should be able to expand it to other files. Is it possible in C++ ?
//N.h
namespace N {
//...
}
//Other.h
#include"N.h"
namespace N { // <--- don't allow this
void foo () {}
}
[Note: Asking this for knowledge and curiosity. Because, have heard many times that one should not expand std.]
AFAIK, you can't do this in C++, and I don't see any practical reason for it either.
You can wrap your code into a class instead of a namespace; since a class declaration cannot be spread over several headers, others cannot add to it.
But again, I don't see why you think this is a problem, and I'd be curious to see an example.
You can only ask people to behave, not force them. Perhaps you can try this:
namespace milind
{
namespace Private
{
// Please don't add stuff to my private namespace
... Important implementation details goes here
}
}
You could use a class with all statics instead of a namespace to simulate the behavior.
Found one way. I can encapsulate the namespace inside another dummy type of namespace and then use it. To avoid verbosity, we can use an alias to the existing namespace.
i.e.
//N.h
namespace DUMMY_ { // <--- put a dummy outer namespace
namespace N {
//...
}
}
namespace N = DUMMY_::N; // alias the name to the original name
//Other.h
#include"N.h"
namespace N { // <--- error !!
void foo () {}
}
Edit: With above solution it's less likely that people would expand namespace N. However, as #Charles comment, still DUMMY_ is visible to the reader. Which means one can still do like:
namespace DUMMY_ {
namespace N { // ok
void foo () {}
}
}
So only way remains to prohibit the undesired expansion is by replacing:
namespace N = DUMMY_::N;
with,
#define N DUMMY_::N
This will work as per expected; but we enter the region of macros.

c++ variable visibility

PLEASE READ THE SECOND EDIT FIRST.
I am looking for books or websites that explain in detailed the c/c++ memory management models. One of the things I am trying to understand is:
namespace A {
SomeClass A;
}
vs
namespace A {
static SomeClass A;
}
vs
SomeClass A;
vs
static SomeClass A;
Thank you very much.
EDIT:
Sorry for the confusion, I mixed the concepts together, and asked the wrong questions.
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.
You use keyword using to introduce a name from a namespace into the current declarative region.
For example:
without using namespace you will write:
#include
int main () {
std::cout << "Hello world!\n";
return 0;
}
However you can also write:
#include
using namespace std;
int main () {
cout << "Hello world!\n";
return 0;
}
This allows you not to append napespace identifier before every
In C++ static class has no meaning unlike other OOP languages. You can have static data members methods.
Instead you can create:
1.A static method in class
class SomeClass
{
public: static void myMethod(int x..)
{
}
}
2.Create a free function in namespace
namespace A
{
void myMethod(int x..)
{
}
}
Latter is better suited when you do not need an object. No class no object...
In both cases enclosing a class within namespace allows you to to group entities under a common name.
First, namespaces are only known until compilation, after that they're non-existant. That said, your first half is no different from your second half in the final program, at least as far as I know. Correct me if I'm wrong please.
Then, if both static SomeClass A and SomeClass A are at global scope (file level), then they're the same too.
Next, if both declarations are inside of a class, struct or function, then the static version will be put into the data segment of the executable too, while the non-static variant will be a normal stack variable.
Again, please, correct me if I'm wrong, but that's it as far as I know it.

Is it possible to treat a template instance as a namespace?

Suppose I have
template< unsigned int num >
class SomeFunctionality
{
static unsigned int DoSomething()
{
//...
}
static void DoSomethingElse()
{
}
};
typedef SomeFunctionality<6> SomeFunctionalityFor6;
Semantically, "SomeFunctionalityFor6" is essentially a namespace specific to the template argument, 6. So in the code using this instance of the template instead of doing
int main()
{
SomeFunctionalityFor6::DoSomething();
}
I'd rather have the ability to use a "using" statement ala a real namespace
int main()
{
using SomeFunctionalityFor6;
DoSomething();
}
This, as I would suspect doesn't work. Visual studio complains that it wants a namespace defined by the "namespace" keyword following any using statement.
Is there anyway to do what I'm trying to do? Mainly I just don't want to fully qualify the namespace everytime I call the static methods. I know its mostly just syntactic sugar, but in my opinion it can make code much more readable. I'm wondering if there's even ways to templatize a namespace directly instead of having to use the "class" keyword.
You can't do that. Neither templatized namespace, nor using class_name.
The only places in the code that can use static functions from a class without qualification are derived classes.
In your case, I would use a typedef for some short name, like
int main()
{
typedef SomeFunctionalityFor6 SF6;
SF6::DoSomething();
}
Or you could just create a local object...
int main()
{
SomeFunctionalityFor6 SF6;
SF6.DoSomething();
}
You could replace/change the SF6 object at will.