What is the right use of "using-declarations"? - c++

I was using this first -
using namespace std::placeholders;
my_cb = std::bind(&Myclass::handler, this, _1, _2);
The code worked fine, but cpplint complained and said I should use "using-declarations", I then changed the code to:
using _1 = std::placeholders::_1;
using _2 = std::placeholders::_2;
my_cb = std::bind(&Myclass::handler, this, _1, _2);
But now compiler complains:
error: ‘_1’ in namespace ‘std::placeholders’ does not name a type
What should be the right using-declarations?
Update
The replies so far suggest me to add back this line:
using namespace std::placeholders;
As I described, cpplint is not happy with using namespace, here is cpplint message:
Do not use namespace using-directives. Use using-declarations instead.
Could you suggest how to do about it?

std::placeholders::_1 is not a type, it's an object of an unspecified type, thus using directive is not applicable to it. Just bring the namespace std::placeholders into a required scope
using namespace std::placeholders;
my_cb = std::bind(&Myclass::handler, this, _1, _2);

The message wants you to write
using std::placeholders::_1;
using std::placeholders::_2;
/*...*/
etc. This is what using declarations are. What you tried with syntax of the form using /*...*/ = /*...*/; are type aliases, a third meaning of using distinct from both using directives (using namespace /*...*/; and using declarations (using /*...*/;).
However, I don't think that is technically allowed at global namespace scope because names starting with an underscore are reserved there. Do it in a narrower scope.
The message is from clang-tidy and implements a particular rule in Google's style guides that flat out forbids any use of using namespace. However, the std::placeholders namespace is specifically designed to be used in this way and avoids making any other names visible. As long as it is used in a narrow scope (not at the global scope) I would consider it fine. Opinions on this rule will differ.

Related

Scope a using declaration, inside a header

Unfortunately I'm bound to using a thirdparty macro which assumes that I am within the namespace thirdparty. However this macro declares some types which I need to be outside of the thirdparty namespace, so I can't use this snippet:
namespace thirdparty
{
TP_MACRO(my_type_name, inner);
}
If I did, all of my declared types would be in the thirdparty:: namespace which won't work.
The issue is that the TP_MACRO is using types from inside of the thirdparty namespace without qualifying them. To get arround the this I am currently bringing these types into the current scope with using declarations:
using thirdparty::type1;
using thirdparty::type2;
TP_MACRO(my_type_name, inner);
The downside of this approach is that I'm polluting the global namespace with these types, which is generally bad practice (this code is in a header file).
I can wrap the above snippet in a new namespace (which I am doing), but I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?
The TP_MACRO is similar to (but is more complex in reality):
#define TP_MACRO (name, inner) \
typedef type1<inner> type1_##name; \
typedef type2<inner> type2_##name;
It is also subject to change, hence why I would avoid copying it's contents.
Try declaring the types in an embedded namespace inside thirdparty so that the macro is happy, then alias that namespace so that it's accessible globally:
namespace thirdparty::myns {
TP_MACRO(my_type_name, inner);
}
namespace myns = thirdparty::myns;
If you are not using C++17, then use:
namespace thirdparty {
namespace myns {
TP_MACRO(my_type_name, inner);
}
}
I can wrap the above snippet in a new namespace (which I am doing)
That's what you should be doing.
I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?
No.
Also I suggest making a recommendation upstream that they improve these macros.

using standard namespace in C plus plus

Consider this
#include<headerfile1>
#include<headerfile2>
.
.
#include<headerfilen>
using namespace std;
when I write this(header files are all in standard library of C++),does std namespace of all header files come into picture?
Also, if there are two libraries h1 and h2 and both have same namespace x and in those namespaces have same function func(). How do I resolve this?
From cppreference:
A using-directive that names the inline namespace is implicitly
inserted in the enclosing namespace (similar to the implicit
using-directive for the unnamed namespace).
For instance, in the following example, using namespace std::string_literals makes the operator visible inside the scope:
{ // in C++14, std::literals and its member namespaces are inline
using namespace std::string_literals; // makes visible operator""s
// from std::literals::string_literals
auto str = "abc"s;
}
If you use the using directive outside a scope (for instance as in your example), pain will follow, as the commenters stated, especially if this file is a header file: this namespace will be implicitly imported to any file that includes this one. This is why the proper way of managing a big project is to create your own namespace and put all your custom objects in that new namespace. If you really must use a using directive, do so in the implementation file, never in the header, and ideally within scopes.
This will help you avoid most conflicts, unless your namespace uses a common name:
namespace Matrix{ <--- Bad practice, Matrix will probably conflict with something
myStuff ...
}
namespace JohnsAwesomeMatrix236790{ <--- Namespace name is unique,unlikely to get conflicts.
myStuff ...
}
Also, it is much safer to import the few functions that you use instead of the entire namespace:
using namespace std; // Imports the entire namespace!
using std::cout; // Much better, we only import
using std::endl; // the names of the two functions we use a lot
Any decently written library you include will make very careful use of the using directive (if at all), so you normally don't have to worry about this. However, if you use code written with less stringent standards (e.g., scientific code) this is something to look out for.

Using Directives in Implementation Files

In C++ Primer, there is one tips says:
One place where using directives are useful is in the implementation
files for the namespace itself.
I guess this is just for using shorthand names? I am not sure how it is different from just surrounding the implementation with
namespace namespace_name
{
}
Thanks.
That applies to modifications to your own namespaces. The purpose of using directives is to import symbols from a different namespace. For example, an infamous idiom:
namespace my_stuff
{
template <typename Container>
void my_fn( Container& xs )
{
using std::begin;
using std::end;
std::sort( begin(xs), end(xs) );
}
}
Everything happens in your my_namespace, but it makes available the std::begin() and std::end() functions if needed. If a more local definition for begin() and end() exists that better matches the Container type, then it will be used instead. If you had simply wrapped everything in the std namespace, this useful ability would be lost.
Hope this helps.
I am not sure how it is different from just surrounding the implementation with namespace namespace_name { }
This is to put your own code within a namespace, as opposed to using some name from another namespace. Say you write a draw function inside the Graphics namespace -- to do this, you wrap draw's code in namespace Math { void draw() { /* some code */ } } and to use it you'd do Graphics::draw. However, when you need to use a function, say, gamma in the Math namespace (which you didn't write), you've to call it Math::gamma for the compiler to know where to search for gamma. Alternatively, you may use shorthand, to drop the Math:: part.
I guess this is just for using shorthand names?
Yes, that's to allow identifiers from some namespace to be used without the qualifier. There are two ways to do it.
Using directive: Use all names in a namespace without qualification (e.g. using namespace Math;)
Using declaration: Use only some specified names without qualification (e.g. using Math::gamma) -- this is usually better than the former.
However, both are encouraged to be used only in an implementation/source file and not in a header to avoid some sources which may have its own copy of gamma and don't want to use Math::gamma, but since you've it in the header, it'll lead a clash of the names. More details on "using namespace" in c++ headers.

using std::<type> v.s. using std namespace [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 7 years ago.
Two ways to use the using declaration are
using std::string;
using std::vector;
or
using namespace std;
which way is better?
It depends.
If you want to inject a single name into another scope, the using-declaration is better, e.g.
namespace foolib
{
// allow vector to be used unqualified within foo,
// or used as foo::vector
using std::vector;
vector<int> vec();
template<typename T> struct Bar { T t; };
template<typename T>
void swap(Bar<T>& lhs, Bar<T>& rhs)
{
using std::swap;
// find swap by ADL, otherwise use std::swap
swap(lhs.t, rhs.t);
}
}
But sometimes you just want all names, which is what a using-directive does. That could be used locally in a function, or globally in a source file.
Putting using namespace outside a function body should only be done where you know exactly what's being included so it's safe (i.e. not in a header, where you don't know what's going to be included before or after that header) although many people still frown on this usage (read the answers at Why is "using namespace std" considered bad practice? for details):
#include <vector>
#include <iostream>
#include "foolib.h"
using namespace foo; // only AFTER all headers
Bar<int> b;
A good reason to use a using-directive is where the namespace only contains a small number of names that are kept intentionally segregated, and are designed to be used by using-directive:
#include <string>
// make user-defined literals usable without qualification,
// without bringing in everything else in namespace std.
using namespace std::string_literals;
auto s = "Hello, world!"s;
So there is no single answer that can say one is universally better than the other, they have different uses and each is better in different contexts.
Regarding the first usage of using namespace, the creator of C++, Bjarne Stroustrup, has this to say in §14.2.3 of The C++ Programming Language, 4th Ed (emphasis mine):
Often we like to use every name from a namespace without qualification. That can be achieved by providing a using-declaration for each name from the namespace, but that's tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use a using-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using a using-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book. [...]
Within a function, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful with using-directives in the global scope. In particular, don't place a using-directive in the global scope in a header file except in very specialized circumstances (e.g. to aid transition) because you never know where a header might be #included.
To me this seems far better advice than just insisting it is bad and should not be used.
using std::string; and using std::vector;.
Polluting the global namespace with a bunch of symbols is a bad idea. You should just use the std namespace prefix too, so you know that you're using standard library containers. Which is better than both options IMO.
If you are simply using the standard library and nothing else and never will be adding in any other libraries to your project, by all means, use using namespace std; - Whatever you feel more comfortable with in that situation. The convention of "never use using namespace std;" comes from the fact that multiple other libraries define things such as string, vector and such. It is good practice to never import the whole namespace, but it should cause no bothers in your case.

What's the purpose of: "using namespace"?

There are convincing arguments against using namespace std, so why was it introduced into the language at all? Doesn't using namespace defeat the purpose of namespaces? Why would I ever want to write using namespace? Is there any problem I am not aware of that is solved elegantly by using namespace, maybe in the lines of the using std::swap idiom or something like that?
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops; or using namespace boost::assign;)
Brevity is also a strong argument. Would you really enjoy typing and reading std::placeholders::_1 instead of _1? Also, when you write code in functional style, you'll be using a myriad of objects in std and boost namespace.
Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
template <class T>
void smart_swap(T& a, T& b)
{
using std::swap;
swap(a, b);
}
If swap is overloaded for some type of T in the same namespace as T, this will use that overload. If you explicitly called std::swap instead, that overload would not be considered. For other types this falls back to std::swap.
BTW, a using declaration/directive does not defeat the purpose of namespaces, since you can always fully qualify the name in case of ambiguity.
Most of the times it is just a shortcut for writing code. You can import names into your enclosing context. I usually restrict it to .cpp files, because when you include an using directive into a .h file, it pollutes all the files in which it is included. Another good practice is restricting the using namespace to the most enclosing environment possible, for instance, inside of a method body declaration. I see it as a convenience, no more, and similar to namespace aliasing, such as:
namespace po = boost::program_options;
and then you can write
po::variables_map ...
The main reason why using namespace was introduced was backwards compatibility: If you have lots of pre-namespace code using lots of (pre-standard versions of) standard library functions and classes, you want a simple way to make that code work with a standard conforming compiler.
BTW, the argument dependent lookup rules at least for C++98 mean that using namespace std::rel_ops will not do what you want in templates (I don't know if this changed in a later version of the standard).
Example:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
}
using namespace std::rel_ops;
int main()
{
X x;
bar(x); // won't work: X does not have operator>
}
Note that putting the using namespace in namespace foo won't help either.
However, using declarations in the right spot help:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
using std::rel_ops::operator>;
}
int main()
{
X x;
bar(x); // now works: operator> found per ADL via the using declaration in `namespace foo`
}
People specifically object to using namespace std; but not to using namespace BigCorp; or to referring to std::cout (which is using the namespace, just not using it, if you know what I mean.) Also, most of the objections to using namespace std are in a header file. In a source file, where the effects can be immediately seen, it's less harmful.
Namespaces are an incredibly useful concept that allow me to have a class called Date even though a library I'm using has a class called Date. Before they were added to the language, we had to have things like GCDate and GCString (my company, Gregory Consulting, predates std::string). Making use of namespaces (with or without the using keyword) lets us all write cleaner, neater code. But when you have to say Gregcons::string every time, you kind of lose the cleaner, neater part. [Disclaimer: I don't actually use my own string class anymore - imagine some appropriate name conflict.] That's the appeal of the using statement. Keep it out of headers, don't apply it to std, and you should generally stay out of trouble.
I find it useful when working with libraries with deeply nested namespaces. The Boost library is one such example. Imaging typing boost::numeric::ublas::matrix<double> m all over the place ...
The thing to avoid is doing using namespace in a header file as this has the potential for royally screwing up any program that includes said header. Always place using namespace statements in .cpp/.cxx files, so that it's restricted to file scope.
"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. Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace"
More information here:
http://www.cplusplus.com/doc/tutorial/namespaces/