0

Here, the context of polymorphic is expecting 'Derived' from 'Base&.

Given

class P { };
class Q : public P { };
auto operator + (const P& p, int x) -> DYNAMIC_DECLTYPE(P) {
    DYNAMIC_DECLTYPE(P) p2(p);
    p2.func(x);
    return p2;
}

Is there a way to have DYNAMIC_DECLTYPE working? I want to use this form instead of

template <typename T> T operator + (const T& t, int x)

or have a potentially long list of

if (!strcmp(typeid(p).name(), typeid(derived()).name()) { ... }

because the latter cannot be used to restrict T to P or subclasses thereof (prove me wrong, if possible).

2
  • Use the template form and add a static_assert(std::is_base_of<P, T>::value, "Boo"); to your code. Your code cannot work as it is, since you would at the very least have to convert p to its actual type, too.
    – Kerrek SB
    Dec 16, 2011 at 12:15
  • if (typeid(p) == typeid(derived)) is enough. if (!strcmp(typeid(p).name(), typeid(derived()).name()) not needed. Dec 16, 2011 at 12:16

1 Answer 1

1

What you are trying to do is in every sense of the word a template pattern: You have an unbounded family of return types with matching function argument types. This should simply be a straight template.

If you want to restrict the permissible types, you should add some typetrait magic. Perhaps like this:

#include <type_traits>

template <typename T>
typename std::enable_if<std::is_base_of<P, T>::value, T>::type
operator+(T const & t, int x)
{
    T s(t);
    s.func(x);
    return s;
}

(If func returns a reference, you can shortcut this to return T(t).func(x);.)

1
  • I believe the return type needs to be 'typename std::enable_if<std::is_base_of<P, T>::value, T>::type'
    – Dave S
    Dec 16, 2011 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.