vendredi 25 mai 2018

Inherit from const type passed as template parameter

The following code is not valid:

struct base {
};

struct inherit : const base {
};

You cannot inherit from a const type.

Does the situation change when templates are involved? In other words, is this code valid:

struct base {
};

template<typename T>
struct inherit : T {
    using T::T;
};

int main() {
    inherit<base const>{};
}

gcc is says it is fine, but clang reports

<source>:6:2: error: 'const base' is not a direct base of 'inherit<const base>', cannot inherit constructors

        using T::T;

        ^        ~

<source>:10:2: note: in instantiation of template class 'inherit<const base>' requested here

        inherit<base const>{};

        ^

1 error generated.

Compiler returned: 1

To make clang happy, I need to do something like this:

template<typename T>
struct inherit : T {
    using U = std::remove_const_t<T>;
    using U::U;
};

Which version is correct? Or are neither of them correct and I need to inherit from std::remove_const_t<T>?

Aucun commentaire:

Enregistrer un commentaire