when I'm reading some c++ sample code for beginner , I'm puzzled at the usage of toupper in the following line :
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
from the above line, I know that "transform" is from namespace std , but I don't know which namespace does toupper come from . maybe there is a default namespace for c++ but
that is just my guess. so could you explain the usage of toupper here to me ?
If you include
<cctype>
then toupper() is in namespace std. If you include
<ctype.h>
then toupper() is in the global namespace. (The one everything ends up in if not defined in a specific namespace. The one you refer to with a leading :: when you're in a specific namespace.)
The same rule applies to <cstring> vs. <string.h>, <cstdlib> vs. <stdlib.h> etc.
If you are puzzled from the ::toupper syntax, it is telling you that in this case, the function is in the global namespace. You can always prepend a double colon to a name and that will tell the compiler to check in the global namespace and not search from your inner namespace out.
void foo() { std::cout << "global"; }
namespace inner {
void foo() { std::cout << "inner"; }
void call() {
foo(); // prints inner
::foo(); // prints global
::inner::foo(); // prints inner (fully qualified namespace)
}
}
Related
#include <iostream>
#include <string>
#include <cctype>
using std::string;
using std::cin;
using std::cout; using std::endl;
int main()
{
string s("Hello World!!!");
decltype(s.size()) punct_cnt = 0;
for (auto c : s)
if (ispunct(c))
++punct_cnt;
cout << punct_cnt
<< " punctuation characters in " << s << endl;
}
It seems that I can use ispunct() without std:: or declaring using std::ispunct; but I can't do that with std::cout or std::cin. Why is this happening?
It means ispunct is part of the global namespace, rather than the std namespace. This is probably because ispunct is one of the functions brought over from C (hence it is in cctype).
On the other hand, cout and cin are part of the std namespace, not the global namespace.
Edit:
As to why things from C are in the global namespace instead of in the std namespace, I believe it has to do with allowing C code to compile by a C++ compiler with minimal changes, since C++ aims to be compatible with C.
According to the comments, ispunct is allowed, but not required, to be in the global namespace (but is required to be in the std namespace), in <cctype>. However, if you had included <ctype.h> instead, ispunct would be required to be in the global namespace.
C names (those you get from including a xxx.h header from C) are allowed to be in the global namespace in addition to the ::std namespace even if you are including the cxxx version of the header. This has been done because it can be a problem not to have those in the global namespace if you provide the C++ implementation, but not the C implementation (so the actual C headers are from a compiler you don't control).
In your case, ispunct comes from the header ctype.h. While you are including the cctype header, this in turn includes the ctype.h header which declares the symbol ispunct in the global namespace.
C++ headers derived from C (such as <cctype>) are required to put the names of things that they declare in the namespace std and they are permitted to also put them in the global namespace. Formally, this wasn't allowed until C++11, but the old rule that those headers were not allowed to put names into the global namespace could not be implemented reasonably and was commonly ignored.
I am developing a project which works with multiple arithmetic types. So I made a header, where the minimal requirements for a user defined arithmetic type are defined:
user_defined_arithmetic.h :
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
What is troubling me is that when I use code like this:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
I get a compiler error:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
I have never used the <math.h> header, only the <cmath>. I have never used the using namespace std in a header file.
I am using gcc 4.6.*. I checked what is the header containing the ambiguous declaration and it turns out to be:
mathcalls.h :
Prototype declarations for math functions; helper file for <math.h>.
...
I know, that <cmath> includes <math.h>, but it should shield the declarations by the std namespace. I dig into the <cmath> header and find:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
So the namespace std begins after the #include <math.h>. Is there something wrong here, or did I misunderstand something?
Implementations of the C++ standard library are permitted to declare C library functions in the global namespace as well as in std. Some would call this a mistake, since (as you've found) the namespace pollution can cause conflicts with your own names. However, that's the way it is, so we must live with it. You'll just have to qualify your name as arithmetic::sin.
In the words of the standard (C++11 17.6.1.2/4):
In the C++ standard library, however, the declarations (except for
names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
unspecified whether these names are first declared within the global namespace scope and are then injected
into namespace std by explicit using-declarations (7.3.3).
If you really wanted to, you could always write a little wrapper around cmath, along the lines of:
//stdmath.cpp
#include <cmath>
namespace stdmath
{
double sin(double x)
{
return std::sin(x);
}
}
//stdmath.hpp
#ifndef STDMATH_HPP
#define STDMATH_HPP
namespace stdmath {
double sin(double);
}
#endif
//uses_stdmath.cpp
#include <iostream>
#include "stdmath.hpp"
double sin(double x)
{
return 1.0;
}
int main()
{
std::cout << stdmath::sin(1) << std::endl;
std::cout << sin(1) << std::endl;
}
I suppose there could be some overhead from the additional function call, depending on how clever the compiler is.
This is just a humble attempt to start solving this problem. (Suggestions are welcomed.)
I have been dealing with this problem a long time. A case were the problem is very obvious is this case:
#include<cmath>
#include<iostream>
namespace mylib{
std::string exp(double x){return "mylib::exp";}
}
int main(){
std::cout << std::exp(1.) << std::endl; // works
std::cout << mylib::exp(1.) << std::endl; // works
using namespace mylib;
std::cout << exp(1.) << std::endl; //doesn't works!, "ambiguous" call
return 0;
}
This is in my opinion is an annoying bug or at the least an very unfortunate situation. (At least in GCC, and clang --using GCC library-- in Linux.)
Lately I gave it another shot to the problem. By looking at the cmath (of GCC) it seems that the header is there simply to overload the C-functions and screws up the namespace in the process.
namespace std{
#include<math.h>
}
//instead of #include<cmath>
With it this works
using namespace mylib;
std::cout << exp(1.) << std::endl; //now works.
I am almost sure that this is not exactly equivalent to #include<cmath> but most functions seem to work.
Worst of all is that eventually some dependence library will eventually will #inclulde<cmath>. For that I couldn't find a solution yet.
NOTE: Needless to say this doesn't work at all
namespace std{
#include<cmath> // compile errors
}
To transform a string and make it lowercase, we might do the following:
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string str("Sample STRING");
cout << str << endl;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << str << endl;
return 0;
}
I know what std::transform is all about; but what's the scope operator :: doing in front of the function tolower?
If I remove the scope operator then the compiler complains of a function mismatch. If I add std in front of the :: operator then the compiler also complains of a function mismatch. What is the purpose of the scope operator in front of tolower? I don't know what it's called, and I searched everywhere for an explanation but to no avail.
You should #include <algorithm> to use std::transform.
The tolower function you want is defined in ctype.h or cctype. You should include one of these headers. The former declares tolower in the global namespace; the latter declares it in the std namespace.
It's likely that without the ::, you're picking up the function template std::tolower declared in the <locale> header. Of course, this only happens because you have using namespace std;. This is a particular example of how using namespace std; can be dangerous.
The :: with nothing on the left means the name to the right will be "looked up in global scope" and will find the global tolower rather than std::tolower. (Therefore, you should #include <ctype.h> to make sure you get the global declaration.)
:: without a left side bypasses looking in all accessible sub-scopes and forces the use of the root (or global) scope.
I am developing a project which works with multiple arithmetic types. So I made a header, where the minimal requirements for a user defined arithmetic type are defined:
user_defined_arithmetic.h :
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
What is troubling me is that when I use code like this:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
I get a compiler error:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
I have never used the <math.h> header, only the <cmath>. I have never used the using namespace std in a header file.
I am using gcc 4.6.*. I checked what is the header containing the ambiguous declaration and it turns out to be:
mathcalls.h :
Prototype declarations for math functions; helper file for <math.h>.
...
I know, that <cmath> includes <math.h>, but it should shield the declarations by the std namespace. I dig into the <cmath> header and find:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
So the namespace std begins after the #include <math.h>. Is there something wrong here, or did I misunderstand something?
Implementations of the C++ standard library are permitted to declare C library functions in the global namespace as well as in std. Some would call this a mistake, since (as you've found) the namespace pollution can cause conflicts with your own names. However, that's the way it is, so we must live with it. You'll just have to qualify your name as arithmetic::sin.
In the words of the standard (C++11 17.6.1.2/4):
In the C++ standard library, however, the declarations (except for
names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
unspecified whether these names are first declared within the global namespace scope and are then injected
into namespace std by explicit using-declarations (7.3.3).
If you really wanted to, you could always write a little wrapper around cmath, along the lines of:
//stdmath.cpp
#include <cmath>
namespace stdmath
{
double sin(double x)
{
return std::sin(x);
}
}
//stdmath.hpp
#ifndef STDMATH_HPP
#define STDMATH_HPP
namespace stdmath {
double sin(double);
}
#endif
//uses_stdmath.cpp
#include <iostream>
#include "stdmath.hpp"
double sin(double x)
{
return 1.0;
}
int main()
{
std::cout << stdmath::sin(1) << std::endl;
std::cout << sin(1) << std::endl;
}
I suppose there could be some overhead from the additional function call, depending on how clever the compiler is.
This is just a humble attempt to start solving this problem. (Suggestions are welcomed.)
I have been dealing with this problem a long time. A case were the problem is very obvious is this case:
#include<cmath>
#include<iostream>
namespace mylib{
std::string exp(double x){return "mylib::exp";}
}
int main(){
std::cout << std::exp(1.) << std::endl; // works
std::cout << mylib::exp(1.) << std::endl; // works
using namespace mylib;
std::cout << exp(1.) << std::endl; //doesn't works!, "ambiguous" call
return 0;
}
This is in my opinion is an annoying bug or at the least an very unfortunate situation. (At least in GCC, and clang --using GCC library-- in Linux.)
Lately I gave it another shot to the problem. By looking at the cmath (of GCC) it seems that the header is there simply to overload the C-functions and screws up the namespace in the process.
namespace std{
#include<math.h>
}
//instead of #include<cmath>
With it this works
using namespace mylib;
std::cout << exp(1.) << std::endl; //now works.
I am almost sure that this is not exactly equivalent to #include<cmath> but most functions seem to work.
Worst of all is that eventually some dependence library will eventually will #inclulde<cmath>. For that I couldn't find a solution yet.
NOTE: Needless to say this doesn't work at all
namespace std{
#include<cmath> // compile errors
}
I'm a beginner in programming and I often see many programs using the prefix std if they are using any std functions like std::cout, std::cin, etc. I was wondering what is it's purpose ? Is it just a way of good programming or is there more to it ? Does it make any difference for the compiler or is it readability or what ? Thanks.
The STL types and functions are defined in the namespace named std. The std:: prefix is used to use the types without fully including the std namespace.
Option 1 (use the prefix)
#include <iostream>
void Example() {
std::cout << "Hello World" << std::endl;
}
Option #2 (use the namespace)
#include <iostream>
using namespace std;
void Example() {
cout << "Hello World" << endl;
}
Option #3 (use types individually)
#include <iostream>
using std::cout;
using std::endl;
void Example() {
cout << "Hello World" << endl;
}
Note: There are other implications to including an entire C++ namespace (option #2) other than not having to prefix every type / method with std:: (especially if done within a header) file. Many C++ programmers avoid this practice and prefer #1 or #3.
C++ has a concept of namespaces.
namespace foo {
int bar();
}
namespace baz {
int bar();
}
These two functions can coexist without conflict, since they're in different namespaces.
Most of the standard library functions and classes live in the "std" namespace. To access e.g. cout, you need to do one of the following, in order of preference:
std::cout << 1;
using std::cout; cout << 1;
using namespace std; cout << 1;
The reason you should avoid using is demonstrated with the above foo and baz namespaces. If you had using namespace foo; using namespace baz; any attempt to call bar() would be ambiguous. Using the namespace prefix is explicit and exact, and a good habit.
Nobody mentioned in their answer that a using namespace foo statement can be put inside a function body, thereby reducing namespace contamination in other scopes.
For example:
// This scope not affected by using namespace statement below.
void printRecord(...)
{
using namespace std;
// Frequent use of std::cout, io manipulators, etc...
// Constantly prefixing with std:: would be tedious here.
}
class Foo
{
// This scope not affected by using namespace statement above.
};
int main()
{
// This scope not affected either.
}
You can even put a using namespace foo statement inside a local scope (pair of curly braces).
It's a C++ feature called namespaces:
namespace foo {
void a();
}
// ...
foo::a();
// or:
using namespace foo;
a(); // only works if there is only one definition of `a` in both `foo` and global scope!
The advantage is, that there may be multiple functions named a - as long as they are within different namespaces, they can be used unambiguously (i.e. foo::a(), another_namespace::a()). The whole C++ standard library resides in std for this purpose.
Use using namespace std; to avoid the prefix if you can stand the disadvantages (name clashes, less clear where a function belongs to, ...).
It's short for the standard namespace.
You could use:
using namespace std
if you don't want to keep using std::cout and just use cout