c++namespacesscopename-clash

Solving name-clash in cpp file of a class


I would like to call the unscoped function "bar" from "somelib" within the "bar" method of Foo.

// .h
class Foo
{
    int bar();
};

// .cpp
#include "Foo.h"
#include <somelib> // contains unscooped function bar()

int Foo::bar()
{
    return bar(); // unwanted recursive function
}

One way to solve it is to make use of a helper function, such as "bar_helper"

// .cpp
#include "Foo.h"
#include <somelib> // contains unscooped function bar()

// unnamed namespace
namespace
{
    int bar_helper()
    {
        return bar(a);
    }
}

int Foo::bar()
{
    return bar_helper();
}


Solution

  • If the non-member bar function is in the global scope, you can use the scoping operator :::

    int Foo::bar()
    {
        return ::bar();
    }