8

In a class B inheriting from class A, it's possible to use a using declaration to bring members of A into B, even templates, like this:

struct A {
    template <typename T>
    void foo();
};

struct B : private A {
    using A::foo;
};

But can it be done for conversion templates?

struct A {
    template <typename T>
    operator T();
};

struct B : private A {
    using A::operator /* ??? */;
};

There seems to be no way of referring to the template by name, but I would love to be proven wrong or get some clarification.

Apples
  • 3,135
  • 1
  • 21
  • 26
  • 1
    What's the use case? – R Sahu Oct 22 '19 at 04:48
  • @RSahu Presumably to inherit a converting constructor without requiring public inheritance. – Ayjay Oct 22 '19 at 05:11
  • @Ayjay, if that's the case, then use of `private` inheritance is ill-conceived, IMO. – R Sahu Oct 22 '19 at 05:16
  • @RSahu Ayjay is correct. To be more specific, I want to allow some class `C` to inherit from `B`, but `C` should not have access to `A`'s protected methods. However, I want `A`'s public methods to remain public, including this conversion operator. I know I could work around this in a few ways, but I would rather avoid writing extra code for such little benefit. – Apples Oct 22 '19 at 05:24
  • @Apples, that seems like design flaw. I don't know how much control you have over these classes. If you have control of what goes in `A`, you could separate `A` into two classes -- one that `B` can inherit `public`ly and the other `private`ly. – R Sahu Oct 22 '19 at 15:29
  • @RSahu I'm aware of all that - and if you'd like to post that as an answer, go ahead - but if you're trying to say that this is an XY problem, it is not. Consider this a question of syntax, not design. I added the `language-lawyer` tag to hopefully clarify. – Apples Oct 22 '19 at 17:49

1 Answers1

3

As a workaround, you can cast to the base class and convert it explicitly:

struct A {
    template <typename T>
    operator T() {
        return T{};
    }
};

struct B : private A {
    template <class T>
    operator T() {
        return static_cast<T>(static_cast<A&>(*this));
    }
};

int main() {
    A a;
    B b;
    int i_a = a;
    int i_b = b;
}
Ayjay
  • 3,413
  • 15
  • 20