从一个名称空间中调用在多个名称空间中重载的函数 [英] Calling a function overloaded in several namespaces from inside one namespace
问题描述
我有以下代码段:
void foo(double a) {}
namespace bar_space
{
struct Bar {};
void foo(Bar a) {}
}
foo(double)是库中的常规函数. 我有自己的命名空间bar_space和自己的结构Bar.我想为Bar实现foo()的重载,从而使Bar更类似于内置类型.
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.
当我尝试从名称空间中调用原始foo(double)时,出现问题:
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
}
}
在我的Fedora和Mac上的gcc上都无法编译.
This fails to compile on gcc on both my Fedora and Mac.
呼叫
foo(5.0)
从名称空间外部或使用
namespace bar_space
{
::foo(5.0)
}
可以正常工作,但这不能使我的新功能达到我的期望(其他开发人员也在bar_space内工作).
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).
bar_space是否隐藏了原始功能?有没有一种方法可以使bar()内的foo(5.0)可以在没有显式作用域(::)的情况下被调用?感谢您的帮助.
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.
推荐答案
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.
C ++标准的3.3.7节内容为:
Section 3.3.7 of the C++ standard reads:
名称可以由显式隐藏 在一个同名的声明中 嵌套的声明性区域或派生 课(10.2)
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2)
因此,要回答您的问题:在您的示例中,void foo(double a);
被void bar_space::foo(Bar a);
隐藏了 .因此,您需要使用::
作用域确定运算符来调用外部函数.
So, to answer your question: in your example void foo(double a);
is hidden by void bar_space::foo(Bar a);
So you need to use the ::
scoping operator to invoke the outer function.
这篇关于从一个名称空间中调用在多个名称空间中重载的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!