Why regex_search does not require namespace - c++

I'm trying to understand why the code below compiles without problems in VS2012 and GCC 4.8.3:
#include <iostream>
#include <regex>
int main(int argc, char** argv)
{
std::wregex brackets_regex(L"");
std::wcmatch bracket_match;
wchar_t expr[80] = L"";
regex_search(expr, bracket_match, brackets_regex);
}
As far as I could find, regex_search is part of namespace std, but neither of the compilers require std::. Why is that allowed?

That code compiles because of Argument Dependent Lookup. Since the arguments are of types from the std namespace, that namespace is tagged as an 'associated namespace' and name resolution considers candidates from that namespace.
could that cause problems between boost and std namespaces?
It's possible it can create ambiguity, resulting in errors.
namespace A {
struct AA {};
}
namespace B {
struct BB {};
void foo(A::AA, BB) {}
}
namespace A {
void foo(AA, B::BB) {}
}
int main()
{
A::AA a;
B::BB b;
foo(a, b);
}
Also I think some compilers might implement it incorrectly, especially in conjunction with two-phase lookup, resulting in either compiling ill-formed code or failing to compile correct code, or even resolving a name to the wrong entity.
If you're encountering a problem you think might be related to ADL you'll have to provide details to get a more specific answer.

Related

Overload not considered even though it looks like a better match

This is rejected by both gcc (live on godbolt) and clang:
#include <string>
namespace
{
std::string
to_string(char const (&str) [14])
{ return str; }
}
void f()
{
using std::to_string;
char const hello[14] = "Hello, World!";
(void) to_string(hello);
}
The compiler considers each of the std::to_string overloads and conclude with:
error: no matching function for call to 'to_string(const char [14])'
If I remove using std::to_string, my overload is considered and called. Why? How to fix it (other than removing the using)?
The scope of the using declaration matters. It's a proper declaration, so name hiding takes effect. Inside the function the global scope version isn't visible. You need to reintroduce it:
using ::to_string;
using std::to_string;
This using declaration
using std::to_string;
hides the declaration in the global namespace. So the compiler does not see the function ::to_string.
So you have to write
using std::to_string;
using ::to_string;
And make the unnamed namespace inline.
inline namespace
{
// ...
}

Using fully qualified name for std namespace in C++

If name in C++ is not fully qualified, e.g. std::cout, it can lead to an unintentional error, such as mentioned at https://en.cppreference.com/w/cpp/language/qualified_lookup. But using a fully qualified name for ::std namespace, e.q. ::std::cout, is very rare, as I have noticed.
Is there any reason why a fully qualified name for ::std namespace is not used?
And what about using fully qualified name for own created namespaces? Is it good idea?
You are completely right, in the sense that yyyy::xxx can be ambiguous if there is a namespace yyyy and also a class yyyy which are both visible in the same scope. In this case only the full qualification ::yyyy::xxx can solve the ambiguity. The example of your link makes it very clear:
// from cppreference.com
#include <iostream>
int main() {
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
But in practice, it's difficult to create a conflicting std at top level, since most of the includes from the standard library will make it fail:
#include <iostream>
struct std { // OUCH: error: ‘struct std’ redeclared as different kind of symbol
int hello;
};
This means that to create a conflict, you'd need to define local classes or introduce a using clause in another namespace. In addition, nobody will (dare to) call a class std.
Finally, in practice, ::yyyy::xxx is less convenient to read. All this explains why you won't find it very often.
Additional remark
The problem is not so much for std which is well known, but rather for your own namespaces and third party libraries. In this case, the namespace alias would be a better alternative to :::yyyy to disambiguate:
namespace foo {
void printf() { }
}
int main() {
foo::printf(); // ok, namespace is chose because no ambiguity
struct foo {/*...*/ }; // creates ambiguity
//foo::printf(); // error because struct foo is chosen by name lookup
::foo::printf(); // ok, but not if you decide to move the code to be nested in another namespace
namespace mylib = foo ; // or ::foo (see discussion below)
mylib::printf(); // full flexibility :-)
}
Its advantage is a higher flexibility. Suppose for example that you'd move your code to nest it in an enclosing namespace. With the namespace alias, your code could continue to work as is (in the worst case with a minor adjustment in the alias definition). With the global scope resolution, you'd have to change all the statements where the global namespace ::foo would be used.
To maintain big code or better readability or clashes in names, C++ has provided namespace " a declarative region".
A namespace definition can appear only at global scope, or nested within another namespace.
#Sample Code
#include <iostream>
int main()
{
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
In the above code compiler is looking for cout in struct std , but in next line when you use ::std::cout it looks for cout in globally defined std class.
Solution:
#include <iostream>
//using namespace std; // using keyword allows you to import an entire namespace at once.
namespace test
{
void cout(std::string str)
{
::std::cout<<str;
}
}
int main()
{
cout("Hello");//'cout' was not declared in this scope
::test::cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}
Or use the in this way , it is just for better readability
##
using namespace test;
int main()
{
cout("Hello");//'cout' was not declared in this scope
cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}

VS12 cmath polluting global namespace [duplicate]

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
}

Why are some functions in <cmath> not in the std namespace?

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
}

"nice" keyword in c++?

So I was doing some simple C++ exercises and I noticed an interesting feat. Boiled down to bare metal one could try out compiling the following code:
class nice
{
public:
nice() {}
};
int main()
{
nice n;
return 0;
};
The result is a compilation error that goes something like this:
<file>.cpp: In function ‘int main()’:
<file>.cpp:11: error: expected `;' before ‘n’
<file>.cpp:11: warning: statement is a reference, not call, to function ‘nice’
<file>.cpp:11: warning: statement has no effect
And this was using regular g++ on Max OS X, some of my friends have tried in on Ubuntu as well, yielding the same result.
The feat seems to lie in the word "nice", because refactoring it allows us to compile. Now, I can't find the "nice" in the keyword listings for C++ or C, so I was wondering if anyone here had an idea?
Also, putting
class nice n;
instead of
nice n;
fixes the problem.
P.S. I'm a relative C++ newbie, and come from the ActionScript/.NET/Java/Python world.
Update:
Right, my bad, I also had an
#include <iostream>
at the top, which seems to be the root of the problem, because without it everything works just fine.
Maybe the problem is somehow caused by function nice in libc. It is similar to trying to name your class printf.
using namespace std, by any chance?
Edit:
The standard says that standard headers define all their symbols in namespace std (see 17.4.1.2.4).
A footnote, however, also says that the <.h> variants dump their names into the global namespace - but of course no one should be using these ;)
It is a namespace problem but not with namespace std. The header <iostream> is pulling in <unistd.h>
If you try
class nice
{
public:
nice() {};
};
int main(int argc, char *argv[])
{
nice n;
return 0;
}
there is no problem.
Simply add
#include <unistd.h>
and you will get the "expected ‘;’ before ‘n’" error. Namespace std does not enter the picture.
So the solution is the same as before - put class nice in its own namespace and it will not clash with the global ::nice().
Try this version:
#include <iostream>
namespace test
{
class nice
{
public:
nice() {}
};
};
using namespace std;
int main()
{
test::nice n;
cout << "well I think this works." << endl;
return 0;
}
In this case I've defined my own namespace test. Doing so, I can use whatever class names I like, including functions already defined like printf. The only things I can't re-use are reserved words like int or namespace.
Note: if you say:
using namespace test;
As well and refer to nice alone, you'll get this error:
nice.cpp: In function ‘int main()’:
nice.cpp:18: error: reference to ‘nice’ is ambiguous
/usr/include/unistd.h:593: error: candidates are: int nice(int)
nice.cpp:7: error: class test::nice
Which I think explains nicely what's going on - nice now exists in two namespaces and the compiler can't work out which one you mean.
It works fine for me. Did you try the exact code you posted?
extern "C"
{
#include <unistd.h>
}