To avoid scoping everything from the STL, you can type
using namespace std;
To avoid scoping only a few things, you can type:
using std::cout;
using std::cin;
I want to write a library that acts the same way. However, instead of being able to include specific classes, I want to be able to include specific collections of functions.
So, for example, I code:
A collection of string functions
A collection of math functions
They are part of the same namespace, but I can include the chunks I want
This is sudo-ish code, but I think it gets my idea across:
namespace Everything{
namespace StringFunctions{
void str1(string & str);
void str2(string & str);
void str3(string & str);
void str4(string & str);
void str5(string & str);
}
namespace MathFunctions {
void math1(int & num);
void math2(int & num);
void math3(int & num);
void math4(int & num);
void math5(int & num);
}
}
then I want to be able to do something like:
#include "Everything.h"
using Everything::Stringfunctions;
int main(){
str1("string"); //this works, I can call this!
math1(111); //compile error: I've never heard of that function!
return 0;
}
Obviously this does not work, and I am kind of confused on how to divide up my library. I don't want to make them classes and then have to use the "dot operator" everywhere, but I also don't want to include a ton of header files.
Maybe I am going about this the wrong way. I hope everyone can help me take the right approach here.
EDIT:
It works by writing:
using namespace Everything::Stringfunctions;
This is very obvious now in hindsight.
The way that you have written your library in the example that you gave is sufficient.
People can get every function from the namespace Everything::Stringfunctions by using the directive using namespace Everything::Stringfunctions.
You should consider splitting functionality into different headers regardless, otherwise you'll wind up with nightmare compilation times. That said I think using namespace Everything::Stringfunctions; ought to do it (with the extra namespace in there. I didn't try compiling though).
What you want seems to work, provided you use using namespace rather than just using. See here (program compiles and outputs '5').
Related
i have named this as next.h and included in main.cpp snippet
i have created two libraries one for the main function and the other just for having classes
i wanted to practise for OOPS so i suddenly thought of using namespaces to know their full potential but i am getting confused between why it isnt working as intended
#include<bits/stdc++.h>
namespace custom
{
class aries
{
public:
int data;
};
}
namespace custom2
{
class aries
{
public:
double data1;
};
}
#include<bits/stdc++.h>
#include "next.h"
using namespace std;
using namespace custom;
using namespace custom2;
int main()
{
custom2::aries a;
a.data1=5.000;
cout<<a.data1;
return 0;
}
The output for the following program is as follows:
5
...Program finished with exit code 0
Press ENTER to exit console.
My question is it should have been 5.000 but why it is int type and not a double type ?
Okay, just summing up the comments:
don't use the #include <bits/stdc++.h>. Instead, just include every header you need to use in your code separately. Reason: bad code readability and not every compiler supports this directive. More: Why should I not #include <bits/stdc++.h>?
also don't use the using namespace *name* command. For clarity: you can use namespaces, just don't use using, use *namespace name*:: instead, like std::cout. Reason: bad code readability, also you can mess up with names (like when you have function_name function and the namespace also has a function with the same name, then the compiler will not know which to use (or you get an error).
answer to your question: std::cout omits zeros while printing numbers so 5.00 will be just 5, but 5.278 will be 5.278.
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;
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.
I have a problem with including header files in C++. As far as I know, it's not a good design to put using namespace std inside header but I got some error when I try to remove it. Here is my code in header file :
#include <iostream>
#include <string>
//using namespace std;
class Messages
{
public:
Messages(string sender, string recipient,int time);
void append();
string to_string();
private:
int time;
string sender;
string recipient;
string text;
};
I did include <string>. However, If I don't use namespace std, all my strings show errors. I do not want to add using namespace std in header file because it's a bad design. So how do I fix it?
Thanks in advance.
Just write std::string everywhere.
#include <iostream>
#include <string>
//using namespace std;
class Messages
{
public:
Messages(std::string sender, std::string recipient,int time);
void append();
std::string to_string();
private:
int time;
std::string sender;
std::string recipient;
std::string text;
};
Just as a rule of thumb: whenever (even in .cpp files) you are using any of the data types or algorithms from the Standard Library, just prefix it with std::. It's brief enough to type, and it will save you a world of pain.
There are some reasons for advanced users to use using declarations at function scope, e.g. when you want to overload a function (e.g. swap) from the Standard Library to work with your own data types (inside their own namespaces). See e.g. this Q&A on how that works.
The class string is declared inside the namespace std. You have three ways of addressing a class that's inside a different namespace:
By always writing <namespace>::<class>
By explicitly declaring that any reference to <class> actually means 1. above: using <namespace>::<class>;.
By declaring that any reference to a <class> that could not be resolved in the current namespace should also be looked up in an additional namespace: using namespace <namespace>;
Those are sorted in descending order of expressiveness. While 1. is perfectly clear wherever written, 3. can require some looking-up and scratching of heads if you are not familiar with the (possible multiple) namespaces used.
These are also sorted in descending order of typing involved, which is why some people (and especially textbooks) opt for 3.
However, you should never use using ... in a header file, because you are not only messing with the namespace resolution inside your header, but also with that of everyone including your header. This results in namespace collisions, strange errors depending on the order of includes and lots of other headaches. Just don't.
And generally speaking, while there is some pro and con involved with options 1. and 2. in implementation files, option 3. is simply offensive to anyone having to work with your source later on.
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/.