返回类型取决于模板参数类型

returntype depending on template argument type

所以我正在尝试编写算法导数,derivate/evaluate 简单多项式。 我的表达式逻辑如下:常量和变量组合成乘法或加法表达式。 在我的表达式 Class 中,我有方法导数,它应该 return 不同的表达式,具体取决于表达式是加法还是乘法。 这是我的代码:

enum OP_enum {Add, Multiply};

//********

template<typename T>
class Constant {
public:
    Constant(const T & v) : val_(v) {}
    T operator()(const T &) const {
        return val_;
    }
    Constant<T> derivative(){
        return Constant<T>(0);
    }
private:
    T val_;
};

//********

template <typename T>
class Variable {
public:
    T operator()(const T & x) const {
        return x;
    }
    Constant<T> derivative(){
        return constant(1);
    }
};

//********

template<typename L, typename R, OP_enum op>
class Expression {
public:
    Expression(const L & l, const R & r) : l_(l), r_(r) { }


    template <typename T>
    T operator()(const T & x) const {
        switch (op) {
            case Add:
                return l_(x) + r_(x);
            case Multiply:
                return l_(x) * r_(x);
        }
    }

    /*RETURN TYPE*/ derivative() {
        switch (op) {
            case Add:
                return l_.derivative() + r_.derivative();
            case Multiply:
                return l_.derivative() * r_ + l_ * r_.derivative();
        }
    }

private:
    L l_;
    R r_;
};

//********


template<typename L, typename R>
Expression<L, R, Add> operator*(const L & l, const R & r) {
    return Expression<L, R, Add>(l, r);
}

template<typename L, typename R>
Expression<L, R, Multiply> operator+(const L & l, const R & r) {
    return Expression<L, R, Multiply>(l, r);
}

有什么方法可以很好地指定 RETURN TYPE 吗? (应该是

Expression<RETURN TYPE of derivation called on L, RETURN TYPE of derivation called on R, Add>
Expression<Expression<RETURN TYPE of derivation called on L, R, Multiply>, Expression<L, RETURN TYPE of derivation called on R, Multiply>, Add>

取决于是求和还是乘积)

我已经尝试了 std::conditional 和 decltype

的一些东西
auto derivative() {
    if constexpr (op == Ad)
        return l_.derivative() + r_.derivative();
    else if constexpr (op == Multiply)
        return l_.derivative() * r_ + l_ * r_.derivative();
}

如果分支推导出不同的类型,则需要 if constexpr