从一个命名空间内部调用在多个命名空间中重载的函数
我有以下代码片段:
void foo(double a) {}
namespace bar_space
{
struct Bar {};
void foo(Bar a) {}
}
foo(double) 是库中的通用函数。 我有自己的命名空间 bar_space 和我自己的结构 Bar。我想为 Bar 实现 foo() 的重载,从而使 Bar 更类似于内置类型。
当我尝试从命名空间内调用原始 foo(double) 时,出现问题:
namespace bar_space
{
void baz()
{
foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
}
}
在我的 Fedora 和 Mac 上的 gcc 上都无法编译。
调用
foo(5.0)
从命名空间外部
namespace bar_space
{
::foo(5.0)
}
或使用工作正常,但这并不会让我的新函数像我希望的那样好(其他开发人员也在 bar_space 内工作)。
bar_space是否隐藏了原始函数?有没有一种方法可以使 foo(5.0) 从 bar_space 内调用而无需显式作用域(::)?任何帮助表示赞赏。
I have the following code snippet:
void foo(double a) {}
namespace bar_space
{
struct Bar {};
void foo(Bar a) {}
}
foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.
Trouble appears when I attempt to call the original foo(double) from within the namespace:
namespace bar_space
{
void baz()
{
foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
}
}
This fails to compile on gcc on both my Fedora and Mac.
Calling
foo(5.0)
from outside the namespace or using
namespace bar_space
{
::foo(5.0)
}
works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).
Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,有一个概念称为 名称隐藏。基本上,如果嵌套作用域中存在同名的函数/类,则函数或类名称是“隐藏”的。这可以防止编译器“看到”隐藏的名称。
C++ 标准第 3.3.7 节内容如下:
所以,回答你的问题:在你的例子中
void foo(double a);
被void bar_space::foo(Bar a) 隐藏 ;
因此,您需要使用::
作用域运算符来调用外部函数。In C++, there is a concept called name hiding. Basically, a function or class name is "hidden" if there is a function/class of the same name in a nested scope. This prevents the compiler from "seeing" the hidden name.
Section 3.3.7 of the C++ standard reads:
So, to answer your question: in your example
void foo(double a);
is hidden byvoid bar_space::foo(Bar a);
So you need to use the::
scoping operator to invoke the outer function.但是,在您的示例代码中您可以使用类似的东西
However, in your sample code you could use something like that
是的,bar_space 隐藏了原始函数,不,如果没有显式作用域if foo(double) 在全局命名空间中定义,则无法从 bar_space 中调用 foo(5.0)。
Yes, bar_space is hiding the original function and no, you can't make foo(5.0) callable from whithin bar_space without explicit scoping if foo(double) is defined in the global namespace.