Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function overloaded in several namespaces from inside one namespace

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.

like image 773
Christian Askeland Avatar asked Dec 14 '10 10:12

Christian Askeland


3 Answers

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:

A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2)

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.

like image 56
Charles Salvia Avatar answered Sep 22 '22 02:09

Charles Salvia


However, in your sample code you could use something like that

namespace bar_space 
{
    using ::foo;
    void baz()
    {
       Bar bar;
       foo(5.0);
       foo(bar);
    }
}
like image 25
mattanjah Avatar answered Sep 23 '22 02:09

mattanjah


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.

like image 20
Simone Avatar answered Sep 21 '22 02:09

Simone