Create my own pre-name like "std" in C++ [duplicate] - c++

This question already has answers here:
How do you properly use namespaces in C++?
(16 answers)
Closed 9 years ago.
Generally when somebody creates a console program he writes
#include <iostream>
#include <stdlib.h>
int main(){
std::cout<<"hello world"<<std::endl;
system("pause");
}
The std must be included to call cout and endl statements.
When I create a library using the headers and the code in the .h and .cpp, and then I include that library, I must use the name of functions/clases/structs/etc directly. How can I make it so I have to use a pre-word like the std for cout and endl?

It's called a namespace.
You can declare your own stuff inside a namespace like this:
namespace mystuff
{
int foo();
}
To define:
int mystuff::foo()
{
return 42;
}
To use:
int bar = mystuff::foo();
Or, import a namespace, just like you can do with std if you don't want to fully-qualify everything:
using namespace mystuff;
// ...
int bar = foo();

you must define namespace like this
namespace mynamespace {
class A{
int func(){
}
}
void func2(){}
}
you can import namespace like this
using namespace mynamespace;

STD prefix is a namespace.
to define/declare a namespace you can follow that example:
namespace test
{ int f(); };
f belong to the namspace test.
to call f you can
test::f();
or
using namespace test;
....
f();

Related

(c++)can u nest namespaces from extern sources

i have a few headers with namespaces which all follow a certain namepattern
right now they all have a prefix infront of their actual name such as
namespace Xname{//inside name.h
//stuff here
};
namespace Xsomething{//inside something.h
//stuff here
};
now this works pretty good for my usage atm, but my idea is to create one more header that contains a namespace that would collect all the other namespaces so i can access them like so:
#include "mainheader.h"
X::name::stuff
X::something::stuff
this way i would just change the namespace name for new headers in the future like so
X::name::stuff
hello::name::stuff
i cant nest them like this:
namespace x{
namespace something{
//stuff
}
}
You could define the new namespaces inside each other like so
#include <iostream>
namespace Xname{//inside name.h
const int x = 0;
};
namespace Xsomething{//inside something.h
const int y = 1;
};
// Your other header
namespace X {
namespace name = Xname;
namespace something = Xsomething;
}
int main() {
std::cout << X::name::x << "\n";
std::cout << X::something::y << "\n";
}
If I understand you correctly, you can use the using namespace directive for this. Here is an example:
namespace Xname {
struct foo {};
}
namespace X {
namespace name {
using namespace Xname;
}
}
int main()
{
Xname::foo f1; // original
X::name::foo f2; // alternative
}

How does C++ know where to look for the namespace specified using "using namespace ..."?

For eg., when using OpenCV, we specify
using namespace cv;
But where does C++ look down to know where it is defined?
using namespace will not make everything declared in that namespace visible. It will expose only what translation unit "sees".
Consider following code
One.h
#pragma once
namespace ns
{
void function1();
}
Two.h
#pramga once
namespace ns
{
void function2();
}
main.cpp
#include "Two.h" // <-- included only Two.h
using namespace ns;
int main()
{
function2(); // <-- is a ns::function2() located in Two.h
function1(); // <-- error compiler does not know where to search for the function
return 0;
}
What happened here is the compiler created translation unit with all preprocessor directives resolved. It will look something like this:
namespace ns
{
void function2();
}
using namespace ns;
int main()
{
function2(); // <-- OK. Declaration is visible
function1(); // <-- Error. No declaration
return 0;
}
How does C++ know where to look for the namespace specified using using namespace …?
It doesn't.
When you use
using namespace cv;
the scope of search for names (of classes, functions, variables, enums, etc) is expanded. The names are searched in the cv namespace in addition to other scopes in which they are normally searched.

Difference in using namespace (std:: vs ::std::) [duplicate]

This question already has answers here:
why prepend namespace with ::, for example ::std::vector
(5 answers)
Closed 7 years ago.
using ::std::...;
VS
using std::...;
Is there a difference(s)? If so, which one(s)?
I saw this:
using ::std::nullptr_t;
which made me wonder.
In your case, there is most likely no difference. However, generally, the difference is as follows:
using A::foo; resolves A from the current scope, while using ::A::foo searches for A from the root namespace. For example:
namespace A
{
namespace B
{
class C;
}
}
namespace B
{
class C;
}
namespace A
{
using B::C; // resolves to A::B::C
using ::B::C; // resolves to B::C
// (note that one of those using declarations has to be
// commented for making this valid code!)
}
If you are inside another namespace that has its own nested std namespace, then ::std and std are different. A simple example:
#include <iostream>
namespace A {
namespace std {
void foo() { ::std::cout << "foo" << ::std::endl;}
}
//using std::cout; // compile error
using ::std::cout; //ok
using std::foo; // ok
//using ::std::foo; // compile error
}
Though definitely not a good practice to ever have a nested std namespace.
From: http://en.cppreference.com/w/cpp/language/using_declaration
Using-declaration introduces a member of another namespace into
current namespace or block scope
Therefore, if your current scope already has a class with the same name, there will be an ambiguity between the one you introduced and the one in your current namespace/block.
A using declaration is just a subset of a using directive. The using directives is defined as follows (http://en.cppreference.com/w/cpp/language/namespace):
From the point of view of unqualified name lookup of any name after a
using-directive and until the end of the scope in which it appears,
every name from namespace-name is visible as if it were declared in
the nearest enclosing namespace which contains both the
using-directive and namespace-name.
Thus, you can consider these two examples that display the issues that can arise.
It prevents ambiguity between namespaces that share the same name (example 1) as well as ambiguity between class names in different namespaces (example 2).
namespace A
{
namespace B
{
struct my_struct {};
}
}
namespace B
{
struct my_struct {};
}
using namespace A; // removing this line makes B:: resolve to the global B::
int main()
{
::B::my_struct; // from global, will not pick A::B::
B::my_struct; // error: 'B' is ambiguous, there is A::B:: and B::
}
Consider this example which showcases why people shun the use of using namespace std;
using namespace std;
template <typename T>
class vector
{ };
int main()
{
vector<int> v; // which one did you want? ambiguous
::vector<int> v_global; // global one
::std::vector<int> v_std; // std::vector<T>
}
It depends on where you use the using declaration. On a global namespace scope there will be no difference. However, if you have code like
#include <iostream>
#include <vector>
namespace my_namespace {
namespace std {
class vector {
};
}
using std::vector;
}
int main()
{
my_namespace::vector<int> v;
}
it will not compile unless you inform the compiler to search the global namespace -> std namespace -> vector in your declaration by stating using ::std::vector.

Using "using" directive to shorten function definition

I have stumbled upon an unusual to me usage of using namespace directive:
Given a header file WeirdNamespace.h:
namespace WeirdNamespace
{
class WeirdClass
{
public:
int x;
void go();
};
}
I have a matching 'WeirdNamespace.cpp`:
#include "WeirdNamespace.h"
#include <iostream>
using namespace WeirdNamespace;
void WeirdClass::go()
{
std::cout << "Reached go?!" << std::endl;
}
The class is used as follows:
#include "WeirdNamespace.h"
int main(int argc, const char * argv[])
{
WeirdNamespace::WeirdClass c;
c.go();
}
Until now I have never seen the using directive used to avoid reopening the namespace in the cpp file or prefixing method names with the namespace name. Is it a correct usage of the directive? Are there any pitfalls specific to this scenario, except for the usual using namespace caveats?
You might do:
namespace WN = WeirdNamespace;
WN::WeirdClass c;
Now, I got the question! The above is no answer.
Quoting from [7.3.4] Using directive
"During unqualified name lookup (3.4.1), the names appear as if they
were declared in the nearest enclosing namespace which contains both
the using-directive and the nominated namespace."
Hence your definition in the source without enclosing it in the namespace is fine.
Yes it is valid but there is a pitfall:
using namespace NamespaceName will make available all the names in NamespaceName.
So instead you can use using to use only the class name:
#include <iostream>
#include "WeirdNamespace.h"
using WeiredNamespace::WeiredClass;
void WeiredClass::go() {
// ...
}

How do I declare a namespace alias in a header file, then use it in a source file?

I want to put a namespace alias (ie namespace A = B::C) in a header file so I can use it in source files, but the compiler just tells me that its "not a namespace name". Any thoughts?
This is a very simplified axample of what I'm trying to do...
header file:
namespace A{
namespace B{
int getInt();
}
}
namespace AB = A::B;
source file:
#include "header_file.h"
#include <iostream>
int AB::getInt(){ // Error "AB is not a namespace name"
return 123;
}
You need to include the file that declares the namespace in the header file or as the comments say do this:
namespace B { namespace C { } }
namespace A = B::C;
At the point where you create the alias, the compiler must have already seen the aliased namespace.
Therefore, you must #include a file that contains said namespace or you must do this:
// "Forward Declaring" the namespace
namespace B { namespace C { } }
namespace A = B::C;