Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve a name collision between a C++ namespace and a global function?

if I define a namespace log somewhere and make it accessible in the global scope, this will clash with double log(double) from the standard cmath header. Actually, most compilers seem to go along with it -- most versions of SunCC, MSVC, GCC -- but GCC 4.1.2 doesn't.

Unfortunately, there seems no way to resolve the ambiguity, as using declarations are not legal for namespace identifiers. Do you know any way I could write log::Log in the global namespace even if cmath is included?

Thanks.

EDIT: Would anybody know what the C++03 standard has to say about this? I would have thought that the scope operator sufficiently disambiguates the use of log in the code example below.

#include <cmath>

namespace foo
{

namespace log
{

struct Log { };

} // namespace log

} // namespace foo


using namespace foo;

int main()
{
    log::Log x;

    return 0;
}

// g++ (GCC) 4.1.2 20070115 (SUSE Linux)

// log.cpp: In function `int main()':
// log.cpp:20: error: reference to `log' is ambiguous
// /usr/include/bits/mathcalls.h:110: error: candidates are: double log(double)
//     log.cpp:7: error:                 namespace foo::log { }
// log.cpp:20: error: expected `;' before `x'
like image 929
cj. Avatar asked Oct 06 '10 10:10

cj.


1 Answers

I'd suggest:

foo::log::Log x; // Your logging class
::log(0.0); // Log function

Generally I wouldn't write using namespace foo; as there is no point having it in the foo namespace if you're not going to use it and it pollutes the global namespace.

See this related question:
How do you properly use namespaces in C++?

like image 190
Mark Ingram Avatar answered Oct 16 '22 10:10

Mark Ingram