I have a pure virtual class, BaseClass, with no data members and a protected constructor. It exists only to provide the interface for a subclass (which is templated). I want just about all the functionality implemented in the base class. Functions that operate on these typically would return BaseClass&, to allow convenient chaining of operations.
All well and good until I try to throw an instance, returned by reference from one of the functions. In short, I am throwing a reference to an abstract class, but I'm secure in the knowledge that it's guaranteed to be a fully constructed child class instance with all virtual functions intact. That's why the BaseClass constructor is protected. I'm compiling against a C++14 compiler. It's refusing to allow me to throw an abstract class.
One of the main points of the class is that I can construct a subclass, immediately call functions on it to add information, and then throw it, all in one fell swoop:
throw String<72>().addInt(__LINE__).addText("mom says no"); //does not compile
but addText(), very reasonably, returns BaseClass&, and the compiler refuses.
How do I? Moving all the member functions into the subclass seems obscene. I can hack around it by static casting the whole expression before the throw:
throw static_cast<String<72&>( //works, ugly
BaseClassString<72>().addText(where).addText(why).addText(resolution));
and even create a macro to hide the ugly mechanics and ensure some safety, but am I missing something? This seems like case of C++ preventing a perfectly workable technique.