Calling a function overloaded in multiple namespaces from the same namespace

I have the following code snippet:

void foo(double a) {} namespace bar_space { struct Bar {}; void foo(Bar a) {} } 

foo (double) is a common function from the library. I have my own bar_space namespace with my own structure, Bar. I would like to implement the foo () overload for Bar, thereby making Bar more like built-in types.

The problem occurs when I try to call the original foo (double) from the namespace:

 namespace bar_space { void baz() { foo(5.0); // error: conversion from 'double' to non-scalar type 'ssc::bar_space::Bar' requested } } 

This does not compile on gcc on both my Fedora and Mac.

Call

 foo(5.0) 

from outside the namespace or using

 namespace bar_space { ::foo(5.0) } 

it works fine, but it does not make my new function as pleasant as I hoped (other developers also work inside bar_space).

Is bar_space a hidden source function? Is there a way to make foo (5.0) callable from bar_space without explicitly defining the scale (: :)? Any help is appreciated.

+6
c ++ function-overloading
source share
3 answers

In C ++, there is a concept called name hiding . In principle, the name of a function or class is β€œhidden” if there is a function / class with the same name in the nested area. This prevents the compiler from "seeing" the hidden name.

Section 3.3.7 of the C ++ standard states:

A name may be hidden explicitly declaring the same name in a nested declarative region or derived class (10.2)

So, to answer your question: in your example void foo(double a); hiding void bar_space::foo(Bar a); Therefore, you need to use the scope :: operator to call an external function.

+5
source share

Yes, bar_space hides the original function and no, you cannot make foo (5.0) callable from whithin bar_space without explicitly defining the scope if foo (double) is defined in the global namespace.

+1
source share

However, in your sample code, you can use something like this

 namespace bar_space { using ::foo; void baz() { Bar bar; foo(5.0); foo(bar); } } 
+1
source share

All Articles