A viable function with a default argument

The following example is in N4296::13.3.3 [over.match.best]

namespace A 
{
    extern "C" void f(int = 5);
}

namespace B 
{
    extern "C" void f(int = 5);
}

using A::f;
using B::f;

void use() 
{
    f(3); // OK, default argument was not used for viability
    f(); // Error: found default argument twice
}

      

I tried to write something like this:

#include <iostream>

namespace A
{
    void foo(int a = 5){ std::cout << a << "1" << std::endl; }
}

namespace B
{
    void foo(int a = 5){ std::cout << a << std::endl; }
}

using A::foo;
using B::foo;

int main()
{ 
    foo(2); //Error 
}

      

DEMO

But I got a compile time error. Why does the Standard say he's ok?

+3


source to share


2 answers


The difference is in the outer "C" which affects the function's namespace membership:

From http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1138.pdf



What remains is the definition of "the same object" relative to the "extern" C language binding? This is addressed to 7.5ΒΆ6:

"At most one function with a specific name can have a C-language link. Declarations for a function with a C-language link with the same function name (ignoring the name names that qualify it) that appear in different scopes of the namespace refer to the same same function. Two declarations for an object with a C-language link with the same name (ignoring the namespace names that qualify it) that appear in different scope of the namespace refer to the same object. "

+3


source


That, since two functions are imported from their namespace, this means the same function has 2 definitions, you can solve it like this:



#include <iostream>

namespace A
{
    void foo(int a = 5){ std::cout << a << "1" << std::endl; }
}

namespace B
{
    void foo(int a = 5){ std::cout << a << std::endl; }
}

int main()
{ 
    A::foo(2);
    B::foo(3);
}

      

-2


source







All Articles