Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A viable function with a default argument

The following example is given 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 similar:

#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 says that it's OK?


1 Answers

The difference is the extern "C", which affects namespace membership of the function:

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

What remains is the definition of “same entity” with respect to ‘extern “C”’ language linkage? This is addressed by 7.5¶6:

“At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function. Two declarations for an object with C language linkage with the same name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same object.”

like image 175
Suma Avatar answered Dec 14 '25 12:12

Suma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!