Instead of including a whole namespace in a given function, I like to only include the stuff I'm going to use, like:
void doStuff() {
using std::sin;
using std::cos;
...
// do stuff
}
Sometimes this list grows longer. I wanted to slim it down to the following (similar to how it's possible with variable declarations):
void doStuff() {
using std::sin, std::cos;
// do stuff
}
I was surprised to find that this was not possible
(error: expected ';' after using declaration). Is there a reason for why the using is defined this way? Is there another way to include a number of functions from a given namespace consisely (except doing using namespace ...;)?
What I want does not seem to be possible currently. However, from en.cppreference.com:
A using-declaration with more than one using-declarator is equivalent to a corresponding sequence of using-declarations with one using-declarator.
(since C++17)
With the following example:
namespace X {
using A::g, A::g; // (C++17) OK: double declaration allowed at namespace scope
}
This seems to suggest that it might be possible in the future.
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().
So I have to use some members of Boost library and some from the std namespace. Right now, I have using boost::asio::ip::tcp; declared and am calling appropriate members with std:: and for example tcp::iostream server(). Is there any reason why I shouldn't add another using, namely using namespace std; and then call all the std things without std:: prefix? Can these two somehow collide or cause malfunction?
Provided that it is usually considered a bad practice to have using directives that import names from the std namespace (especially when at namespace scope and/or in a header file), because it easily leads to name clashes, consider the following program:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using namespace A;
using namespace B;
foo();
}
How should the compiler resolve the call to foo()? Well, it won't. It is ambiguous, because both A::foo() and B:foo() can now be referred to as the unqualified foo().
If there are entities with the same name in the std namespace and in the global namespace (or in any other namespace for which you have a using directive), ambiguities due to name clashes are likely to arise.
In your specific case, a using directive such as:
using namespace std;
Will be unlikely to clash with the name tcp introduced by your using declaration (notice, that a using declaration imports just one specific name and is, therefore, preferable).
Yet, it is still considered to be poor programming style and you should not do it, regardless of whether you have some other using directive or using declaration already in place.
Yes, they can. The compiler can't resolve the correct namespace in that case. The solution is to use prefixes (for example std::).
You can also put the using namespace keywords inside a function or other block, so the namespace won't be used outside it:
void foo()
{
using namespace ns;
} // ns won't be used after this
Furthermore, namespace usage can be limited to a header:
namespace ns
{
#include "ns.h"
}
However, limiting the namespace to a header is not recommended because it causes problems in many cases.
The other answers do a good job of explaining how ambiguities can be resolved when you have two or more using namespace directives, but it's worth pointing out that the situation is different if you have using declarations that pull in two or more specific names from within namespaces, like this:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using A::foo;
using B::foo;
return 0;
}
The above is always a compile error, even though neither foo is ever used. This is because using declarations, as the name suggests, actually declare a name in their enclosing scope to be an alias to a name in some other namespace. This is in contrast to a using namespace directive, which merely makes names available in their enclosing scope without actually declaring any new names.
If you really want to, it's possible to resolve the above code like this:
using fooa = A::foo;
using foob = B::foo;
But using declarations should usually be avoided anyway, because they have some other semantic surprises which can bite you in unexpected, subtle, and sometimes undetectable ways. The exception is using a base class member within a derived class, which is usually OK, though not often necessary.
this is a technical question as well as (if it's technically feasible) a style question. In my code I have a series of functions that load and manipulate a file. For different syntax these functions exist in separate namespaces, so that:
namespace typeA {
void load();
void manipulate();
};
namespace typeB {
void load();
void manipulate();
};
In this minimal example, obviously I could simple have a clause that checks for the file type and then calls typeA:load() and typeB:load() etc. as required.
However, I was wondering if it is also possible to do this using namespace aliases? It would make the code cleaner as there are several dozen calls to functions in the namespaces which all would need a separate if/else clause.
What I've tried:
namespace my_type = (ft == "type_A") ? typeA : typeB;
...
my_type::load();
which doesn't compile with an error in the namespace alias assignment line.
Is there another way of doing this / what is the generally accepted clean way of handling situations like this?
I suppose a virtual class and inheritance for each file type would be one option. Are there others?
There is no way to do such namespace alias.
3.4.6 Using-directives and namespace aliases [basic.lookup.udir]
1 In a using-directive or namespace-alias-definition, during the lookup for a namespace-name or for a name in
a nested-name-specifier only namespace names are considered.
You an use partial template specialization to solve that.
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
This question already has answers here:
Why is "using namespace X;" not allowed at class/struct level?
(6 answers)
Closed 5 years ago.
I find that my C++ header files are quite hard to read (and really tedious to type) with all the fully-qualified types (which goes as deep as 4 nested namespaces). This is the question (all the answers give messy alternatives to implementing it, but that's not the question): Is there a strong reason against introducing scoped using-directive in structs and classes in the C++ language (while it's permissible to have scoped using-declaration in functions)?
e.g.
class Foo : public Bar
{
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
using Bar::MemberFunc; // no conflict with this
// e.g. of how messy my header files are without scoped using-directive
void FooBar(System::Network::Win32::Sockets::Handle handle, System::Network::Win32::Sockets::Error& error /*, more fully-qualified param declarations... */);
};
Since namespace is a keyword, I would've thought it's distinct enough to cause no conflict with the scoped using declaration such as Bar::MemberFunc.
EDIT: Read the question carefully ---> I've bolded it. Reminder: we're not discussing how to improve readability of the example here. Suggesting how scoped using-directive could be implemented (i.e. by means of adding keywords / constructs etc.) in the C++ language is NOT an answer (if you could find an elegant way to implement this using existing C++ language standards, then it would of course be an answer)!
Sometimes I do this to achieve almost the same effect:
namespace detail {
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
class Foo : public Bar
{
void FooBar(Handle handle, Error& error);
};
}
using detail::Foo;
Given that using declarations at class scope are not inherited, this could work. The name would only be valid inside that class declaration, or inside the declarations of nested classes. But I think it's sort of overloading the concept of a class with an idea that should be larger.
In Java and Python individual files are treated in a special way. You can have import declarations that inject names from other namespaces into the file. These names will (well, not exactly with Python, but it's too complicated to explain here) only be visible within that file.
To me that argues for this sort of ability not being tied to a class declaration, but given a scope of its own instead. This would allow injected names to be used in several class declarations if it made sense, or even in function definitions.
Here is an idea I prefer because it allows these things while still giving you the benefits of a class level using declaration:
using {
// A 'using' block is a sort of way to fence names in. The only names
// that escape the confines of a using block are names that are not
// aliases for other things, not even for things that don't have names
// of their own. These are things like the declarations for new
// classes, enums, structs, global functions or global variables.
// New, non-alias names will be treated as if they were declared in
// the scope in which the 'using' block appeared.
using namespace ::std;
using ::mynamespace::mytype_t;
namespace mn = ::mynamespace;
using ::mynamespace::myfunc;
class AClass {
public:
AClass(const string &st, mytype_t me) : st_(st), me_(me) {
myfunc(&me_);
}
private:
const string st_;
mn::mytype_t me_;
};
// The effects of all typedefs, using declarations, and namespace
// aliases that were introduced at the level of this block go away
// here. typedefs and using declarations inside of nested classes
// or namespace declarations do not go away.
} // end using.
// Legal because AClass is treated as having been declared in this
// scope.
AClass a("Fred", ::mynamespace::mytype_t(5));
// Not legal, alias mn no longer exists.
AClass b("Fred", mn::mytype_t);
// Not legal, the unqualified name myfunc no longer exists.
AClass c("Fred", myfunc(::mynamespace::mytype_t(5));
This is analogous to declaring a block for local variables in a function. But in this case you are declaring a very limited scope in which you will be changing the name lookup rules.
Maybe namespace alias?
namespace MyScope = System::Network::Win32::Sockets;
You can use a typedef inside the class declaration to achieve the same
class Foo : public Bar
{
typedef System::Network::Win32::Sockets::Handle Handle;
typedef System::Network::Win32::Sockets::Error Error;
void FooBar(Handle handle, Error& error);
};
The obvious benefit of namespaces is that they allow you to avoid naming conflicts. However, by introducing an entire namespace into a class declaration, this benefit is voided. It's entirely possible that a function in the System namespace could conflict with your own Bar::MemberFunc function. You even note this in your sample code when you added the comment "no conflict with this".
You obviously don't want to introduce entire namespaces into your class like this:
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
And you can't add more narrowly scoped using statements like this into a class declaration. Putting these directly into a class declaration is illegal.
using System::Network::Win32::Sockets::Handle;
using System::Network::Win32::Sockets::Error;
What you can do is use the unnamed namespace. So, your header file would look something like this:
namespace {
using System::Network::Win32::Sockets::Handle;
using System::Network::Win32::Sockets::Error;
}
class Foo : public Bar
{
using Bar::MemberFunc;
// clean!
void FooBar(Handle handle, Error& error /*, more declarations*/);
};
This has three distinct advantages.
The contents of entire namespaces are not introduced. This helps to more easily avoid naming conflicts.
You have a list, before your class declaration, of what your class depends upon to work correctly.
Your function declarations are clean.
Please correct me if I'm wrong; I only briefly tested this. Quickly wrote up an example, and it compiled.