Search code examples
c++inheritanceusing

`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.


Solution

  • 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); }
    };