Implement templated member function in common base to return derived type

3 days ago 2
ARTICLE AD BOX

Consider this hierarchy of classes:

#include <string> #include <iostream> using namespace std; struct Exception { Exception &operator <<(int i) { value += i; return *this; } int value; }; struct FirstException: public Exception { }; struct SecondException: public Exception { }; int main() { try { throw FirstException() << 3 << 4; } catch (const FirstException &e) { cout << "FirstException " << e.value << endl; } catch (const SecondException &e) { cout << "SecondException " << e.value << endl; } catch (const Exception &e) { cout << "Exception " << e.value << endl; } }

The basic part so far is that one can use the provided operator to increment the value.

Now I'd like to have this operator available in all the descendant classes. Technically it so is already, but the return type is slicing objects, which is particularly problematic with the intended usage of this operator - the exception will be caught as a sliced Exception .

What are the options here?

Repeat (with appropriate return type) the operator into all the derived classes.

Implement something like friend T &operator <<(T &lhs, int i), with a templated member, but that may bother with the temporary object's lifecycle extension, see my related question over here.

Implement CRTP with Dietmar's solution using another indirection.

As far as I understand, with respect to the above situation, the root issue is that it's easy to have a correctly-behaved member function/operator overload that is granted to work on temporary objects. But it's complicated to implement this with a free function.

Can I do this without CRTP?

Read Entire Article