is there any way to put all to functions that are in a header file in a namespace, without change the header itself?
for example, if I have a header file called "funcs.h" which has some functions inside, is there any way to put all the functions inside in a namespace without changing "funcs.h"?
Thank you!
My first idea was some dirty hacks, but there is no reason to use a hack.
Suppose you have a function defined in global scope (actually I use an overload set for the example, and whether this is inside a header or not is not relevant):
void foo() {}
void foo(int) {}
You can make it accessible from within a namespace via using:
namespace ns {
using ::foo;
}
int main() {
ns::foo();
ns::foo(1);
}
Just be aware that you now have ns::foo and ::foo both refering to the same function (set of overloads, resp.).
Related
when I was studying a book on C++, I came across this.
if we declare a class,
class student {public:
void func(int v1,int v2)
{
//some code
}
//some members.
};
and use a function with same name out of the class (non-member function) like,
void func(int x,inty)
and If I wish to call this non-member function in the member function of the above declared class, the syntax would be,
//inside the member function...
::func(x,y);
}
correct me if I am wrong.otherwise,
assuming I wrote
using namespace std;
in the beginning of the program, Is the below code equivalent to previous one?
//inside the member function
std::func(x,y);
}
and, does the answer change if I use a different namespace other than std?? ie,
provided I use,
using namespace abc
are the following declarations
abc::func(x,y)
and,
::func(x,y)
absolutely equivalent under any conditions or do they change under specific conditions??
Thank you.
in the beginning of the program, Is the below code equivalent to previous one?
//inside the member function
std::func(x,y);
No it isn't. Because you preform a qualified name lookup. It means you specify exactly in what namespace func is to be defined. std::func, if it exists, still belongs the the std namespace, not the global one.
A using namespace directive only makes identifiers available to unqualified name lookup, where it's up to the compiler to figure it out. This point is quite intricate, I know, but it's the reason namespaces can be considered useful.
The problem kicks in when you collide the names.
Do not do using namespace std;, since it can cause collision problem.
These code are identical:
using namespace std;
sort(params...); // Omitted, this will call std::sort
std::sort(params...);
And even if you are using namespace std, std::sort calls the same functions as long as std::std doesn't exist (and defining it from user side is illegal code).
However, abc::func() is not identical to ::func(). :: in the beginning means root namespace, which is the most outside namespace. There's no ambiguity or implicit filling in this case.
The using namespace directive allows your code to use stuff that is in the specified namespace. You can even have several of them:
using namespace x;
using namespace y;
This means that a function call like func() will call the function whose code resides either in x or in y namespace (or, in fact, in the global namespace).
If your code looks like this
using namespace x;
using namespace y;
void func(int, int) {... code ...}
then the func function goes in the global namespace, not in the x or y namespace. That is, ::func refers to this function, while x::func and y::func don't.
To put your code (class, function, etc) in a namespace, use this code:
namespace x
{
void func(int, int) {... code ...}
class student
{
void func(int, int) {... code ...}
};
}
Then, if you want to call the func that is outside your class, you can use x::func() or ::x::func(), but cannot use ::func().
If I declare it in .h in obvious way:
namespace <named_namespace> {
namespace {
…
<type> <function>(<parameters>);
…
}
}
and put its implementation in .cpp, a compilation error will occur:
'<type> <named_namespace>::{anonymous}::<function>(<parameters>)' should have been declared inside <named_namespace>
Is it possible to avoid this error without putting the function's implementation in the single file? Currently I use keyword static instead, but it produces multiply annoying warnings:
'<type> <named_namespace>::<function>(<parameters>)' declared 'static' but never defined
which, as I've understood, can be disabled only by keeping function in a single file (header or source).
Cross-compiler solution is welcome (if any).
Or maybe splitting the header file into 'public' and 'private' parts is more efficient?
You cannot have anonymous namespace that works across translation units therefore putting anonymous namespace in .h won't work as you expect. In each translation unit (.cpp), that namespace is assigned a different, unique name.
Separated declaration and definition is possible but only inside that namespace:
namespace {
void func();
}
…
namespace {
void func()
{
…
}
}
I've got an argument with my colleague.
We have a class that is a member of a namespace (which is a member of the other namespace but that is not important here I think). In the header file, we nest the class block into the namespace block like this:
namespace NS {
class A {
void method();
// ...
};
}
And here is the .cpp file and the subject of our argument. I wrote:
using namespace NS;
void A::method() {
// ...
}
The colleague told me that I use the 'using' directive improperly, and I should have used here the same NS { ... } as in the header. (He's modified the code and got some compiler errors that he only managed to get rid of by removing the using directive and surrounding the code with NS { ... }.)
My point is that 'using' just affects the name lookup so A is looked for in the NS namespace, so my approach is correct, and his compiler problems were caused by something else but not by that 'using' directive.
Who is right and why?
Added: guys, please don't answer like 'I did this (or that) way many times', that's not much useful. We need the theory here: why this or that approach is right or wrong.
Your colleague is correct, you should wrap cpp with namesapce which means you define your funcitons inside namesapce NS.
namespace NS
{
void A::method()
{
// ...
}
}
You may get conflict name lookup if you have multiple A available.
The dangerous thing happening here is that the using declaration takes a snapshot of whatever entities named A::method in namespace NS have been seen by the time the using declaration is encountered.
Have a read of Google cpp style guilde regarding namespace, also 101 c++ coding standards
Both of you are right in different ways. You are right in that the using directive will let the compiler resolve A in void A::method() to be NS::A, but he is also right in that in most cases you are better off opening the namespace.
The reason is that not everything that is declared in the namespace in the header will be looked up, and for those elements you will need to open the namespace (or provide the qualification manually), so it makes sense to provide a uniform approach.
A common example is the definition of operators that are applied to the type:
// header
namespace NS {
class A { ... };
std::ostream& operator<<(std::ostream&,A const&);
}
// implementation file (incorrect):
using namespace NS;
std::ostream& operator<<(std::ostream& o, A const & a) {
// do something
}
The problem here is that function definitions (when the function name is not a qualified name) are self-declaring. In the header the operator is declared as ::NS::operator<<, but in the implementation file it is defined as std::ostream& ::operator<<(std::ostream&, NS::A const&). The using directive will allow the resolution of the A identifier to be NS::A, but it won't make that function definition reside in the NS namespace.
This leads to a subtle problem, where any use of that operator will find ::NS::operator<< due to ADL, but that operator is not defined anywhere (although there is a similar operator in a different namespace)
Having said all that, there are some coding conventions (where I work now has such a guideline) that require namespaces for all types and that free function definitions should be performed outside of the namespace and always qualified to avoid self declarations. In the example above, the operator would be defined in the implementation file as:
std::ostream& ::NS::operator<<(std::ostream& o, A const& a) { ... }
But unless you really get used to always qualifying, this is prone to errors if you forget the qualification of the function.
namespace NS {
class A {
void method();
// ...
};
}
Always done it that way...
It turns out it's not only "coding-style matter". Using namespace ... leads to linking error when defining and initializing a variable declared extern in header file. Take a look at example in my question. Definition of constant within namespace in cpp file
You are correct. I've been bitten by this a number of times (that is, bitten by thinking that using declarations don't do this). There are three ways you could write this, and all will work:
namespace NS
{
void A::method()
{ }
}
Or:
NS::A::method() { }
Or:
using namespace NS;
A::method() { }
However, in terms of style, I would suggest either the first or the second - using declarations can get hairy when you have multiple classes with the same name and methods around.
It is considered good practice not to use 'using namespace' in code declarations or libraries but its OK to use them for the actual program's code.
Ie: dont use it for the Cpp definition but you can use it when your calling the function/class outside.
This is all just good coding practice and unless other people are using your code it matters more what you want.
The best is to put the cpp code into Namespace { ... } for readability
In C++ definition file (.cpp), sometimes I can define small functions to be invoked, for example:
// Class declaration
// Myclass.h
Class Myclass
{
...
void Classfunction();
...
}
// Class defination
// Myclass.cpp
#include "Myclass.h"
...
void helper_fun()
{
...
}
...
void Myclass::Classfunction()
{
...
helper_fun();
...
}
In the above example, we can see void helper_fun() is declared and defined in the .cpp file. The purpose of this function is to be invoked by the functions that have been defined in the class. Of course, the helper_fun can be declared in the head file first and then defined in the implementation file. My question is whether this is a good practice for C++ code writing. Moreover, does this practice have some bad effects? Thanks!
It would be good practice to have the helper_fun defined in an anonymous namespace within the source file.
Like this:
namespace {
void helper_fun()
{
//...
}
}
Reason being that if another helper_fun is defined in another source file with the same signature, you wouldn't have any risk with linkage errors. It's not to say that there will be, but rather, there could be one.
Also, you shouldn't put functions in your header if it's not going to be used outside of the respective source file.
Having local helper functions in the source files are very common. Normally they are either declared as static (e.g. static void helper_fun() { }) or in an anonymous namespace (e.g. namespace { void helper_fun() { } }).
Making the functions static or having them in an anonymous namespace is so that they wont be callable from the outside, and so that you can have more local functions with the same name.
If, however, you want to call the function from other source files, then define the function normally, and add a declaration in the header file.
If you need it to be public, and included in other files via the header file. Then put it there.
Otherwise there's no reason for it to be in the header.
If you declare helper_fun in the header, it becomes visible to users of Myclass.h. Do you want helper_fun to be used elsewhere?
By keeping it solely within Myclass.cpp you ensure it can only be used by code within Myclass.cpp.
Of course declare functions in .cpp files is ok. It is helper function, so, you shouldn't give its declaration to user. You can use anonymous namespace for internal linkage (by default functions has external linkage).
An unnamed namespace or a namespace declared directly or indirectly
within an unnamed namespace has internal linkage.
like this
namespace
{
// helper_fun has internal linkage.
void helper_fun()
{
}
}
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.