Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`using` Only Some Overloads Of A Base Class

Consider a class b with two overloaded methods of foo:

struct b {
    void foo(float) {}
    void foo(const char *) {}
};

If I derive d privately from b, I can use using to expose b's foo:

struct d : private b {
    using b::foo;
};

However, this exposes all overloads. Is there a way to expose only one of them (say, the float one)? For example, in the following, I'd like the last line to fail compilation:

d t;
t.foo(3.13); // d should have this overload
t.foo("hello"); // d shouldn't have this overload

I tried various ways of writing

    using b::<i mean only void foo(float), dammit!>

but couldn't get any of them to compile.

Also, obviously it's possible to define in d just the required overload calling b's overload

struct d : private b {
    void foo(float f) { b::foo(f); }
};

but the question is if it's possible to do this tersely with using only.

like image 596
Ami Tavory Avatar asked Sep 22 '16 07:09

Ami Tavory


People also ask

Is it possible to overload a function in derived class which has been inherited from base class?

The reason is the same as explained in the case of the C++ program. In C#, just like in C++, there is no overload resolution between class Base and class Derived. Also, there is no overloading across scopes and derived class scopes are not an exception to this general rule.

Can we overload a function of superclass in derived class?

You can override or overload a function in the derived class. If you have another function with the same name as the inherited function but different parameter lists it is called overloading functions. Both of these can exist.

Does function overloading work with inheritance?

Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ.

Is inheritance mandatory for overloading in Java?

Java doesn't support multiple inheritance. In multilevel inheritance, one class is inherited by other class. And some other class can also inherit the child class. Class Y is subclass of class X and class Z is subclass of class Y.


1 Answers

No, that is not possible. A using declaration, just like any other declaration, operates on names.

using b::foo; introduces the name foo into the declaration's containing scope, such that it refers to whatever b::foo refers to. The name b::foo refers to a "family" of overloaded functions, so after the using-declaration, the name foo refers to the same.

If you want to "publish" only some overloads, you have to do it using the trampoline functions you've shown:

struct d : private b {
    void foo(float f) { b::foo(f); }
};
like image 92
Angew is no longer proud of SO Avatar answered Nov 02 '22 21:11

Angew is no longer proud of SO