Are name spaces required for free functions in the STL? - c++

I'm playing around with my coding style. I used to explicitly prefix every library call with std:: but I'm switching over to using declarations like this:
using std::count;
using std::vector;
One thing I've noticed over the past few days is that sometimes if I forget a using declaration -- using std::vector; is a good example -- I get reams of compiler errors. However, if I neglect to namespace delcare an algorithm such as using std::count; my code compiles just fine.
Does this have to do with the difference with classes and free functions? On all the reference sites, both count(first, last, value) and vector are prefixed with std:: so I would expect them to behave the same.
Or does it have to do with other functions in the global namespace? I notice std::max also seems to require a namespace declaration, perhaps it defined in a default-included Apple/glibc/LLVM file and thus there is a conflict if I used it sans namespace declaration?
I am using Apple LLVM 7.0.2. on El Capitan.
EDIT: Show us the code
#include <algorithm>
#include <vector>
using std::count;
using std::vector;
int main() {
vector<int> v = { 1, 2, 3, 4 };
return count(begin(v), end(v), 3);
}

As T.C. (almost) said, the magic incantation is ADL, which stands for "argument-dependent lookup". When a function is called with an argument whose type is defined in a namespace, the compiler looks for the function in that same namespace. Makes, sense, right?

Related

C++ compilling errors when using Quadprog++ with Eigen together

this is my first question here, I've searched it all over for a long time yet no solution.
I'm using QUadprog++ to solve a quadratic problem. When I use it in a test alone, it was alright. But when I implement it into my project, which contains Eigen, the Eigen operations will have errors like "Matrix A has no member named ‘lu_inverse’". If I comment the header files of Quadprog++ (Array.hh and Quadprog++.hh) out, the errors just disappear. So I assume that it was a conflict error between the header files of Eigen and Quadprog++. Does anyone have some clue? Thanks in advance!
You can also switch to one of QuadProgpp versions which can work with Eigen types directly: https://github.com/asherikov/QuadProgpp, https://www.cs.cmu.edu/~bstephe1/eiquadprog.hpp; or try an alternative implementation of the same algorithm (also Eigen based) https://github.com/asherikov/qpmad.
if your using namespace quadprogpp; then dont. your different libraries have the same typenames and thats causing the errors you have. It may be a few more characters to type quadprogpp::someFunction(); but its worth it. This is also why you shouldn't ever put a using namespace in a header ever. Its because you pollute all files that include that header with the namespace symbols and name conflicts can ensue which is the same kind of error your having right now.
the Quadprog library is in it's own namespace.
#if !defined(_ARRAY_HH)
#define _ARRAY_HH
#include <set>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
namespace quadprogpp {
enum MType { DIAG };
template <typename T>
class Vector
notice how just after the #includes there is a decleration of namespace quadprogpp{} and everything that is defined in its enclosing brackets will be defined in scope to quadprogpp, so to use any of this library you have to prefix eveything with the namespace name. this is no different than using things from the standard library. I'm quite sure you've written the standard c++ hello world
#include<iostream>
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}
cout and endl being part of namespace std have to be prefixed with std:: to access them. Many new programmers to c++ dislike this and one of the very first things they google is how to not have to type out namespaces.
#include<iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
the next thing new programmers often do is learn to place their definitions in header files and their program logic in cpp files. Thats when they commit the next common mistake.
#ifndef MYHEADER
#define MYHEADER
#include<string>
#include<vector>
#include<iostream>
using namespace std; //Never do this in a header.
doing that pollutes all of your code with everything in the standard library. That may seem like a trivial thing but when you start using another library or perhaps you create your own type that has the same name as things in the standard library that causes name collisions.
That's when the compiler simply cant reason about which Vector you want. But both Quadprog.hh and Array.hh in Quadprog++ are wrapped in namespace quadprogpp to specifically prevent name collision, which is the whole purpose of namespaces. So there is somewhere in your code, likely a header file, where you've made the statement of using namespace quadprogpp;, or some other namespace that defines an Array type, and the compiler can't deduce which type your referring to in your code.
Other than removing your using namespace statements you can also prefix a typename with its namespace qualifer to disambiguate which type your talking about. In your case I'm confident your Array should be declared as quadprogpp::Array arraynamme; rather than simply Array arrayname;

Implicit “using namespace std” without writing it in the source code

I have a C++ code that uses endl, vector, complex, and cout occasionally without any namespace qualification. When compiling with GCC 4.9, I get errors like this one:
bfm.h:454:4: error: 'complex' does not name a type
complex<double> inner(Fermion_t x,Fermion_t y);
^
In the very same file, there are lines with an std:: qualifier:
std::complex<Float> dot(Fermion_t x_t, Fermion_t y_t,int sx,int sy);
Throughout the codebase, I saw the following template specializations used
std::complex<double>
std::complex<cFloat>
complex<Float>
complex<double>
complex<T>
complex<S>.
Neither for the regular express struct\s+complex nor class\s+complex I managed to find something in the codebase or the codebase of the base library. Therefore I assume that it indeed is the standard library complex type.
There are a couple of using namespace std scattered around in various header files, but not all of them.
I tried compiling this codebase with GCC 4.9 and Clang 3.7. Both give similar errors about the missing type. Is there some possibility that this has worked with an older version of GCC? I have tried to insert std:: at all the needed points but I have the impression that I do something wrong if I cannot just compile the source checkout that is meant for this type of computer.
you can use selective using... declarations or type aliasing to bring in only the std:: members you need. Like:
using std::complex;
using std::cout;
using std::endl;
cout << "Hello world" << endl; // works
complex<float> x; // works
fstream y; // compile error, no namespace qualification, no using declaration
std::fstream z; // OK
Ah, yes, maybe not that evident, so perhaps worth mentioning. You now that std::endl? Well, it's a stream manipulator, a function in fact.
Which means one can bring in the current block function members from other namespaces as well.
Like:
#include <cmath>
#include <cstdlib>
inline void dummy(float x) {
float y=fabs(x); // Na'a.., fabs is imported into std namespace by <cmath>
using std::itoa; // same is itoa, but we'll be using it
char buff[128];
itoa(42, buff, 10); // OK
}

Functions in namespace std accessible in global scope

Under some situations, it seems like I can access functions that should be in the std namespace without a using or std:: qualifier. So far, I've only seen this occur with functions from the algorithm library.
In the following example, I expect all_of() to be in the std namespace, but this code compiles without error in VS2013 (Microsoft Compiler 18).
#include <iostream>
#include <string>
#include <algorithm>
int main() {
const std::string text = "hey";
std::cout << all_of(begin(text),end(text),islower);
return 0;
}
Changing std::cout to cout without adding a using namespace std or using std::cout generates an "undeclared identifier" error as expected.
What's going on here?
This probably happens due to Argument-Dependent Lookup. The iterator returned by begin(text) and end(text) is probably a class defined in namespace std (or nested in a class in namespace std), which makes namespace std associated with it. Looking up unqualified names for function calls looks into associated namespaces, and finds all_of there.
By the way, this is exactly the same reason why calling begin(text) works, even though the function template begin() is defined in namespace std. text is a std::basic_string, so std is searched.

Using Directive C++ Implementation

In C, if I use #include "someFile.h", the preprocessor does a textual import, meaning that the contents of someFile.h are "copy and pasted" onto the #include line. In C++, there is the using directive. Does this work in a similar way to the #include, ie: a textual import of the namespace?
using namespace std; // are the contents of std physically inserted on this line?
If this is not the case, then how is the using directive implemented`.
The using namespace X will simply tell the compiler "when looking to find a name, look in X as well as the current namespace". It does not "import" anything. There are a lot of different ways you could actually implement this in a compiler, but the effect is "all the symbols in X appear as if they are available in the current namespace".
Or put another way, it would appear as if the compiler adds X:: in front of symbols when searching for symbols (as well as searching for the name itself without namespace).
[It gets rather complicated, and I generally avoid it, if you have a symbol X::a and local value a, or you use using namespace Y as well, and there is a further symbol Y::a. I'm sure the C++ standard DOES say which is used, but it's VERY easy to confuse yourself and others by using such constructs.]
In general, I use explicit namespace qualifiers on "everything", so I rarely use using namespace ... at all in my own code.
No, it does not. It means that you can, from this line on, use classes and functions from std namespace without std:: prefix. It's not an alternative to #include. Sadly, #include is still here in C++.
Example:
#include <iostream>
int main() {
std::cout << "Hello "; // No `std::` would give compile error!
using namespace std;
cout << "world!\n"; // Now it's okay to use just `cout`.
return 0;
}
Nothing is "imported" into the file by a using directive. All it does is to provide shorter ways to write symbols that already exist in a namespace. For example, the following will generally not compile if it is the first two lines of a file:
#include <string>
static const string s("123");
The <string> header defines std::string, but string is not the same thing. You haven't defined string as a type, so this is an error.
The next code snippet (at the top of a different file) will compile, because when you write using namespace std, you are telling the compiler that string is an acceptable way to write std::string:
#include <string>
using namespace std;
static const string s("123");
But the following will not generally compile when it appears at the top of a file:
using namespace std;
static const string s("123");
and neither will this:
using namespace std;
static const std::string s("123");
That's because using namespace doesn't actually define any new symbols; it required some other code (such as the code found in the <string> header) to define those symbols.
By the way, many people will wisely tell you not to write using namespace std in any code. You can program very well in C++ without ever writing using namespace for any namespace. But that is the topic of another question that is answered at Why is "using namespace std" considered bad practice?
No, #include still works exactly the same in C++.
To understand using, you first need to understand namespaces. These are a way of avoiding the symbol conflicts which happen in large C projects, where it becomes hard to guarantee, for example, that two third-party libraries don't define functions with the same name. In principle everyone can choose a unique prefix, but I've encountered genuine problems with non-static C linker symbols in real projects (I'm looking at you, Oracle).
So, namespace allows you to group things, including whole libraries, including the standard library. It both avoids linker conflicts, and avoids ambiguity about which version of a function you're getting.
For example, let's create a geometry library:
// geo.hpp
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
and use some STL headers too:
// vector
template <typename T, typename Alloc = std::allocator<T>> vector;
// algorithm
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
But now, if we use all three headers in the same program, we have two types called vector, two functions called transform (ok, one function and a function template), and it's hard to be sure the compiler gets the right one each time. Further, it's hard to tell the compiler which we want if it can't guess.
So, we fix all our headers to put their symbols in namespaces:
// geo.hpp
namespace geo {
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
}
and use some STL headers too:
// vector
namespace std {
template <typename T, typename Alloc = std::allocator<T>> vector;
}
// algorithm
namespace std {
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
}
and our program can distinguish them easily:
#include "geo.hpp"
#include <algorithm>
#include <vector>
geo::vector origin = {0,0,0};
typedef std::vector<geo::vector> path;
void transform_path(geo::matrix const &m, path &p) {
std::transform(p.begin(), p.end(), p.begin(),
[&m](geo::vector &v) -> void { geo::transform(m,v); }
);
}
Now that you understand namespaces, you can also see that names can get pretty long. So, to save typing out the fully-qualified name everywhere, the using directive allows you to inject individual names, or a whole namespace, into the current scope.
For example, we could replace the lambda expression in transform_path like so:
#include <functional>
void transform_path(geo::matrix const &m, path &p) {
using std::transform; // one function
using namespace std::placeholders; // an entire (nested) namespace
transform(p.begin(), p.end(), p.begin(),
std::bind(geo::transform, m, _1));
// this ^ came from the
// placeholders namespace
// ^ note we don't have to qualify std::transform any more
}
and that only affects those symbols inside the scope of that function. If another function chooses to inject the geo::transform instead, we don't get the conflict back.

What requires me to declare "using namespace std;"?

This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare
using namespace std;
in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.
Consider the two following functions that use swap().
#include <iostream>
#include <algorithm>
namespace zzz
{
struct X {};
void swap(zzz::X&, zzz::X&)
{
std::cout << "Swapping X\n";
}
}
template <class T>
void dumb_swap(T& a, T& b)
{
std::cout << "dumb_swap\n";
std::swap(a, b);
}
template <class T>
void smart_swap(T& a, T& b)
{
std::cout << "smart_swap\n";
using std::swap;
swap(a, b);
}
int main()
{
zzz::X a, b;
dumb_swap(a, b);
smart_swap(a, b);
int i, j;
dumb_swap(i, j);
smart_swap(i, j);
}
dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.
smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.
Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.
//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\n"),
std::bind2nd(std::less_equal<int>(), 0)
);
IMO, in code like this std:: just makes for line noise.
I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).
Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)
The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.
First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:
std::cout << "I am accessing stdout" << std::endl;
Firstly, the using directive is never required in C since C does not support namespaces at all.
The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:
using namespace std;
string myString;
is equivalent to:
std::string myString;
Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:
using std::string;
string myString;
This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.
Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:
File common1.h:
namespace intutils
{
int addNumbers(int a, int b)
{
return a + b;
}
}
Usage file:
#include "common1.h"
int main()
{
int five = 0;
five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.
using namespace intutils;
five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}
So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
using std::cout;
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds
Layne
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.