Namespace information compromises the readability in C++ - c++

I'm new to C++ and had a background in C. The one thing which is quite difficult for me to adopt is to frequently use scope operator e.g. std:: Well, i'd avoid it usage by putting using namespace std at the start of my source code but a lot of people doesn't use this method as they think this may bite them in future.
Plus, the visual-studio also shows error/warning messages along scope operator e.g.
cannot convert from 'std::vector<int,std::allocator<_Ty>> *' to 'std::shared_ptr<std::vector<int,std::allocator<_Ty>>>'
Though the above message is verbose but its such a pain to read it (?). I think it can be simple to read if it was in this form
cannot convert from 'vector<int,allocator<_Ty>> *' to 'shared_ptr<vector<int,allocator<_Ty>>>'
1) Why everyone is using std::, even for cout, cin, endl ? Why would anyone use the labels for some other purpose anyways?
2) Is their a workaround in Visual studio to not show me error/messages/syntax-highlights with a prefix std:: ?

Although, as pointed out in the comments, code like using namespace std; is considered bad practice, you can avoid repeated use of the namespace prefix in code like std::cout, by specifying individual scoped elements in using statements.
Something like this:
using std::cout; //
using std::cin; // You can, from then on, just use 'cout', 'cin' and 'endl'
using std::endl; //
For very common elements, like those listed in the above code, you can put the relevant using lines in a header file - typically, your 'global' header that you use to build your precompiled header.

For starters there is a difference in name lookup for qualified and unqualified names.
Consider for example the following program.
#include <iostream>
class A
{
private:
int x = 10;
public:
operator int() const { return x; }
friend void f( const A & )
{
std::cout << "f( const A & )\n";
}
};
void f( int )
{
std::cout << "f( int )\n";
}
int main()
{
const A a;
f( a );
::f( a );
return 0;
}
The program output is
f( const A & )
f( int )
Secondly using using directives can result in name collisions or selecting a wrong function due to the overload resolution.
Apart of this the code can be less readable because the reader will not know for example whether endl is std::endl or a user defined function defined in some namespace that is included in the name lookup due to numerous using directives.
There are situations when you need to use an explicit or an implicit using directive.
For example if you want to use declarations from the namespace std::placeholders or when you want to declare an inline namespace. But the scope of these directive is usually very limited. Another example is using using declarations. But again try to make their scopes as small as possible.

Inside a limited scope, for example within a function, it's logical to use using namespace std or any other using.
Repeating namespace names is tedious when you can avoid it at no cost. I 've seen lots of code infested with std::, especially when it comes to the usage of std::forward, std::move, std::function, std::thread etc.
C++ keywords like using are there for a reason; Unconditionally saying that "using namespace std is bad" is erroneous.

To answer your 2), I believe the answer is "No, there's no way to change the way VS writes out error messages to strain out all the std::".
The good news is that these error messages used to be much worse. You'd get error messages for all N variations on a given template, and then have to parse out the tiny spec of signal from the ocean of noise. Not fun. Heaven help you if you were using nested templates like std::vector<std::vector<std::string> > >.
So while template error messages can still be a bit verbose, the information presented is actual information, not spam spam spam eggs and spam without the eggs.
Oh, and >> used to always parse as a stream operator, so you had to add spaces between the >s for a nested template. UP HILL, BOTH WAYS!!!

Related

How to use a shorter name for `setw`, `setprecision`, `left`, `right`, `fixed` and `scentific`?

I would like to use these STL functions in my code, but so many times that their presence makes the readability of the code cumbersome. Is there any way to define "aliases" for these commands?
iomanipulators are functions and to most of them you can easily get a function pointer (actually I didn't check, but for example having several overloads or function templates, would make it less easy):
#include <iostream>
#include <iomanip>
int main(){
auto confu = std::setw;
auto sing = std::setprecision;
std::cout << confu(42) << sing(3) << 42;
}
I cannot help myself but to mention that your motivation is rather questionable. C++ programmers do know stuff from the standard library. The do not know your aliases. Hence for anybody but you readability will be decreased rather than improved. If you have complicated formatting you can wrap the printing in a function:
my_fancy_print(42);
Readers of C++ code are used to functions, they know where to look for their implementation and my_fancy_print(42) is not confusing, while std::cout << confu(42) << sing(3) << 42; is a source of surprise: I would have to look for definition of confu and sing just to realize that they are just aliases for something that could have been used directly.

variables defined in a scope v.s. namespace variables injected in that scope

When I run this code, it displays 6...
#include <iostream>
namespace X {
int p = 5;
}
using namespace X;
int p = 6;
int main()
{
std::cout << ::p;
return 0;
}
However, when I run this code, it displays 5...
#include <iostream>
namespace Y {
int p = 16;
}
namespace X {
int p = 5;
using namespace X;
}
int main()
{
std::cout << X::p;
return 0;
}
Can anyone explain what's happening there? Why am I not getting any error about ambiguity?
First, your question itself. In the first example, you use...
std::cout << ::p;
That prepended :: resolves namespaces in a specific order, starting with the local namespace. (See this answer). Thus, it looks for p globally, locally, and then in an external namespace (X). Because it found p locally, it stops looking.
In the second example, you are explicitly resolving your namespace:
std::cout << X::p;
Thus, there's no search order to be bothered with. It is just going to look for p in the namespace X, and fail otherwise.
This leads to the second problem: you appear to be confusing the purpose of the using namespace keywords. Those are intended to enable you to use a more shorthand approach of resolving to a namespace, instead of always using the fully qualified name (x::p).
However, the computer will still look in the local namespace first, and THEN the using namespaces in the order they are found. As always, once the computer finds the thing named in a namespace, it stops looking.
This leads to a major principle in C++: don't use using namespace! There are exceptions, but you'll pick up on those as you work. The issue comes down to ambiguity as to what namespace something will be coming from, which is exactly the problem you described.
For example, imagine you define the namespaces X and Y in separate classes, and then you simply have the following...
#include "x.hpp"
#include "y.hpp"
using namespace x;
using namespace y;
int main()
{
std::cout << p << std::endl;
}
Where'd p come from? Looking at x.hpp and y.hpp, you see that BOTH havep, so which one is used? And then, what if you addusing namespace z;above them? Now you have to check ifzhasp`. ARGH!
(See this answer for more information on namespace resolution.)
It is important to note that, as far as the compiler/linker are concerned, there is no ambiguity. It has an implicit resolution order to handle that. The ambiguity is all on the coder.
Even worse, what if you define q locally, without realizing that x or y have a q as well? What will it resolve to?
This is a situation you never want to create! Borrowing from Tim Peter's Zen of Python (albeit, different language, but some of the principles therein are true in most languages)...
Explicit is better than implicit.
So, how can we write this to be less wibbly-wobbly timey-wimey?
Drop using namespace. The only time you should even touch this is if you are using a bunch of stuff from one namespace, and virtually nothing from anywhere else. (You'll notice most C++ programmers won't even do using namespace std;)
Use the fully qualified name on anything you use sparingly-to-moderately. For example, x::p.
If you use something a lot, use the command using x::p at the top of the file. This resolves p to namespace x, without confusing everything else.
In short, you should be able to tell, at a glance, what namespace everything comes from. Never create a situation of ambiguity and implicit resolution; only bugs and pain lie that way.

C++ performance: using declaratives Vs using declarations Vs using names directly from the library

I use using declarations more than using the explicit std:: way for using the standard library objects. I got this question of whether is there any performance increase with using using declarations, using declaratives and using names directly from the standard library.
For instance:
To print out "Hello world" we can write the following ways:
By using the bare std:: way:
std::cout << "Hello world";
By using using declaration:
using std::cout; cout << "Hello world";
By using using declarative:
using namespace std; cout << "Hello world";
So, Which of the above methods has the best perfomance? and more efficient?
All three methods will result in the same runtime code, and thus performance. (easily verified by switching to assembly output, e.g. g++ -O3 -S test.cpp).
Should you be talking about compile time, it is very unlikely that this would have any measurable impact. Theoretically fully qualifying the name (::std::cout) could reduce the number of potential symbols that need to be checked. However, disk I/O will in all likelihood be far more significant. In fact, I ran a test compiling a simple program 100 times in three variants: ::std::cout, std::cout and using namespace std; cout. Even when compiling without optimizations (to make symbol lookup as significant as possible) and on a fast SSD (to minimize disk I/O times) any difference was below the noise level.
This has no effect on run-time performance. using is applied at compile time
These methods are fully the same to compare in run-time, because using is previously compiled.
But if you want to create your own namespace you should be careful.
#include <iostream>
namespace test
{
int a = 1;
}
using namespace test;
int main()
{
int a = 3;
std::cout << test::a << std::endl; // prints 1
std::cout << a << std::endl; // be careful, prints 3
return 0;
}
When you are using the method above you make your namespace global. It means that when you declare another variable a in the main() function, it will hide the variable a from test. You can still have the access to this variable by typing test::a, but a without test:: will refer to the local variable.
To avoid it, don't use using namespace your_namespace if you don't need it. It's better to write one more word to make your code safe.
If you are using some variables from namespace very often you could declare it in this way using your_namespace::variable.

How to print the name of a variable with parameters?

I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
Let me explain a simpler case with a toy solution based on a macro:
int i = 1771;
I can print the variable_name with
#define toy_solution(x) cout << #x ;
If I execute
toy_solution(i);
"i" will be printed.
Now, imagine there is a well-allocated table T.
I would like to write in the program:
solution(T[i]);
and to read on the screen "T[1771]".
An ideal solution would treat the two cases, that is :
ideal_solution(i) would print i.
ideal_solution(T[i]) would print T[1771].
It is not important to me to use a macro or a function.
Thanks for your help.
#define toy_solution(x, i) cout << #x << "[" << i << "]"
I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
well, as you did not understand my comment, I'll say out loud in an answer:
what you want to do is not possible
You have to choose between either #Alin's solution or #lizusek.
I think that #lizusek's solution is better because you're writing C++ code, so if you can do something that gives the same result than with using macros, you should use plain C++ code.
edit: let my try to explain why this is not possible
so what you want is:
f(T[i]) -> T, i
The only way you could write that so it would make sense in preprocessor is:
#define f(T[i]) cout<<#T#<<#i#
but then the preprocessor will give an error, because you can't index an array as a function (even a macro function) parameter:
test.c:5:12: error: expected comma in macro parameter list
#define f(T[i]) cout<<#T#<<#i#
^
If you try to do the same thing using a C++ function, then it's even more non-sense, as a function call such as:
toy_solution(t[i]);
would actually be translated to the value t[i] points to at runtime, so inside the function you'll never be able to known that the given value was actually in an array. So what you want is wrong, and you should stick to good coding practices: using a function and if what you want is:
toy_solution(t[i]);
then use:
toy_solution("t", i);
Possible solutions that you should never use
well, when I say it's not possible, it's that the only solutions I can think off are so twisted that you'd be insane to actually use them in your code… And if you do, I hope I'll never read one of your code or I may become violent :-) That's why I won't show you how or give you any code that could help do what I'm about to tell you.
use a template system
You could either write your code using your own template system or use one commonly used for HTML processing to process your source code through it and apply a transformation rule such as:
toy_solution(t[i]) -> toy_solution("t", t[i])
it's definitely possible, but it makes your build chain even more complicated and dependant on more tools. C/C++ build toolchain are complicated enough, please don't make it worst.
Or you code make your own fork of C and of a C compiler to change the syntax rules so what you want becomes possible. Though, I personnally would never use your fork, and then I'd go trolling and flaming about this on HN, deeply regretting to have given you such a bad idea :-)
use a custom class to encapsulate your arrays in
if you do something like:
template<T>
class Element {
T value;
List<T> _owner;
[…]
}
template<T>
class List {
Element<T> values[];
std::string _name;
[…]
}
so that when you call the function
toy_solution(T[i]);
the implementation would look like:
void toy_solution(Element<T> e) {
std::cout<<e.get_list_name()<<" "<<e.get_value()<<std::endl;
}
but that's sooo much boilerplate and overhead just to avoid doing a simple function definition that does not look as nice as you dream of, that I find it really stupid to do so.
You can write a function as simple as that:
void solution( std::string const& t, int i) {
std::cout << t << "[" << i << "]";
}
usage:
int i = 1771;
solution( "T", i);
You can also write a macro, but be aware that this is not type safe. Function should be preferred.

Should I use an enum or multiple const for non-sequential constants in c++?

I'm writing porting file-io set of functions from c into a c++ class. "Magic numbers" (unnamed constants) abound.
The functions read a file header which has a number of specific entries whose locations are currently denoted by magic numbers.
I was taught by a veteran programmer a couple years back that using "magic numbers" is inherently evil, and thus, I have since tried to avoid using unnamed constants in my port. So I want to create some sort of list of constants of where the entries are stored.
So far I've come up with two solutions that seem relatively safe -- use a namespace enclosed set of constants or a namespace enclosed enum.
Can I use either solution safely? Would there be any advantages to one over the other?
e.g.
OPTION 1
namespace hdr_pos {
const unsigned int item_1_pos=4;
const unsigned int item_2_pos=8;
const unsigned int item_3_pos=12;
const unsigned int item_4_pos=24;
const unsigned int item_5_pos=32;
};
OPTION 2
namespace hdr_pos {
enum e {
item_1_pos=4,
item_2_pos=8,
item_3_pos=12,
item_4_pos=24,
item_5_pos=32
};
};
Is there anyway to prevent duplicates, to catch if I change the positions due to a future update to the file header, but forget to change one of them?
Please keep this factual and non-subjective. If there is no advantage you know of, feel free to answer that.
Note: I would use more descriptive names, of course, in my actual implementation; I just called things item_<#>_... for examples sake...
I can see two advantages to using an enum. First, some debuggers can translate constants back into enum variable names (which can make debugging easier in some cases). Also, you can declare a variable of an enumerated type which can only hold a value from that enumeration. This can give you an additional form of type checking that you wouldn't have simply by using constants.
Checking to see if a value is duplicated might depend on your particular compiler. The easiest way to do so would probably be to write an external script that will parse your enum definition and report whether or not a value is duplicated (you can run this as part of your build process if you like).
I've dealt with this situation before, for error codes.
I have seen people using enums for error codes, and this pose some issues:
you can assign an int to the enum that doesn't not correspond to any value (too bad)
the value itself is declared in a header, meaning that error code reassignment (this happens...) breaks code compatibility, you also have to take care when adding elements...
you have to define all codes in the same header, even if often times some code are naturally restricted to a small portion of the application, because enums cannot be "extended"
there is no check that a same code is not assigned twice
you cannot iterate over the various fields of an enum
When designing my error codes solution, I thus chose another road: constants in a namespace, defined in source files, which address points 2 and 3. To gain in type safety though, the constants are not int, but a specific Code class:
namespace error { class Code; }
Then I can define several error files:
// error/common.hpp
namespace error
{
extern Code const Unknown;
extern Code const LostDatabaseConnection;
extern Code const LostNASConnection;
}
// error/service1.hpp
// error/service2.hpp
I didn't solved the arbitrary cast issue though (constructor is explicit, but public), because in my case I was required to forward error codes returned by other servers, and I certainly didn't want to have to know them all (that would have been too brittle)
However I did thought about it, by making the required constructor private and enforcing the use of a builder, we're even going to get 4. and 5. in a swoop:
// error/code.hpp
namespace error
{
class Code;
template <size_t constant> Code const& Make(); // not defined here
class Code: boost::totally_ordered<Code>
{
public:
Code(): m(0) {} // Default Construction is useful, 0 is therefore invalid
bool operator<(Code const& rhs) const { return m < rhs.m; }
bool operator==(Code const& rhs) const { return m == rhs.m; }
private:
template <size_t> friend Code const& Make();
explicit Code(size_t c): m(c) { assert(c && "Code - 0 means invalid"); }
size_t m;
};
std::set<Code> const& Codes();
}
// error/privateheader.hpp (inaccessible to clients)
namespace error
{
std::set<Code>& PrivateCodes() { static std::set<Code> Set; return Set; }
std::set<Code> const& Codes() { return PrivateCodes(); }
template <size_t constant>
Code const& Make()
{
static std::pair< std::set<Code>::iterator, bool > r
= PrivateCodes().insert(Code(constant));
assert(r.second && "Make - same code redeclared");
return *(r.first);
}
}
//
// We use a macro trick to create a function whose name depends
// on the code therefore, if the same value is assigned twice, the
// linker should complain about two functions having the same name
// at the condition that both are located into the same namespace
//
#define MAKE_NEW_ERROR_CODE(name, value) \
Make<value>(); void _make_new_code_##value ();
// error/common.cpp
#include "error/common.hpp"
#include "privateheader.hpp"
namespace error
{
Code const Unkown = MAKE_NEW_ERROR_CODE(1)
/// ....
}
A tad more work (for the framework), and only link-time/run-time check of the same assignment check. Though it's easy to diagnose duplicates simply by scanning for the pattern MAKE_NEW_ERROR_CODE
Have fun!
The title of your question suggests that the main reason you have doubts about using a enum is that your constants are non-iterative. But in C++ enum types are non-iterative already. You have to jump through quite a few hoops to make an iterative enum type.
I'd say that if your constants are related by nature, then enum is a pretty good idea, regardless of whether the constants are iterative or not. The main disadvantage of enums though is total lack of type control. In many cases you might prefer to have strict control over the types of your constant values (like have them unsigned) and that's something enum can't help you with (at least yet).
One thing to keep in mind is that you can't take the address of an enum:
const unsigned* my_arbitrary_item = &item_1_pos;
If they're purely constants and require no run-time stuff (like can't init enum with non-enum value) then they should just be const unsigned ints. Of course, the enum is less typing, but that's besides the point.