views:

112

answers:

2

Hi,

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'
+4  A: 

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:
http://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c/41598

Mark Ingram
+2  A: 

Although it does not help you, the error from GCC 4.1.2 is incorrect. The log in log::Log can only refer to a class or namespace name.

If your code also needs to compile with GCC 4.1.2, then there are two options:

  1. Use the fully qualified name foo::log::Log
  2. Use a namespace alias:

    namespace log1 = foo::log;
    log1::Log logger;
Bart van Ingen Schenau
+1 for the idea of using an alias. Are you sure the error is incorrect? I presume you mean that the scope operator resolves the ambiguity because it cannot be applied to a function name? I'm not sure what the standard says about this special case. But regarding namespace definitions, see section 7.3.1: "The identifier in an original-namespace-definition shall not have been previously defined in the declarative region in which the original-namespace-definition appears."
cj
I am sure the error is incorrect. I had to look it up in the standard, and according to the grammar only a class or namespace name can occur before the scope operator. The declaration of your `log` namespace is not a problem, because it is not being defined in the same namespace as the `log` function. (namespace is withing `foo` namespace, function is in global namespace)
Bart van Ingen Schenau