I have a base class that defines a constrained templated conversion operator
struct base {
template
Sometimes you can "solve" this issue by using a conversion constructor - but this is not always possible (like converting to pointer T).
Following trick requires GNU g++, with C++14.
If some_constraints
and different_constraints
are mutually exclusive, you can add using base::operator auto;
in derived
class to make all the conversion operators of base
available.
Example:
struct Base {
protected:
// conversion to pointer types (protected).
template<typename T, typename= typename std::enable_if<std::is_pointer<T>::value>::type>
operator T() const;
};
struct Derived : public Base{
// Make all Base conversion operators public.
using Base::operator auto;
// conversion to default constructible & non-pointer types.
// added an extra typename=void to distinguish from Base template operator.
template<typename T, typename= typename std::enable_if<!std::is_pointer<T>::value>::type,typename=void>
operator T() const;
};
Live demo
To achieve a similar effect, you could move the constraints inside the operator and call the base conversion operator if the constraints are not satisfied:
struct base {
template <typename C, std::enable_if_t<some_constraints<C>, int> = 0>
operator C() const;
};
struct derived : base {
template <typename P>
operator P() const {
if constexpr (different_constraints<P>) {
// Overridden operator
} else {
return base::operator P();
}
}
};
Or equivalently have one regular std::enable_if_t<different_constraints<P>, int> = 0
conversion operator and another std::enable_if_t<!different_constraints<P>, int> = 0
that calls the base conversion operator.
I would say it is not possible. and even if it was, your derived operator would hide base one as template argument is not part according to namespace.udecl#15.sentence-1:
When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list, cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting)
Unfortunately, template parameter doesn't count and both conversion operator
has empty parameter-type-list, are const
and no ref-qualifier.