如何解决C ++名称空间和全局函数之间的名称冲突? [英] How to resolve a name collision between a C++ namespace and a global function?

查看:115
本文介绍了如何解决C ++名称空间和全局函数之间的名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在某处定义名称空间log并使其在全局范围内可访问,则它将与标准cmath标头中的double log(double)冲突.实际上,大多数编译器似乎都支持它-大多数版本的SunCC,MSVC,GCC-但GCC 4.1.2却没有.

不幸的是,似乎没有办法解决歧义,因为using声明对于名称空间标识符不合法.您知道我可以在全局名称空间中写log::Log的任何方式吗?

谢谢.

编辑:有人知道C ++ 03标准对此要说些什么吗?我本以为作用域运算符在下面的代码示例中充分消除了log的使用.

#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'

解决方案

我建议:

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

通常我不会写using namespace foo;,因为如果您不打算使用using namespace foo;名称空间,那么在foo名称空间中就没有意义了.

请参阅以下相关问题:
如何在C ++中正确使用名称空间?

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'

解决方案

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++?

这篇关于如何解决C ++名称空间和全局函数之间的名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆