I have a ServerCall
class that sends a request to the server and receives a JSON response. I want the response to be used to build an object whose type is defined by a template argument.
template<typename RetType>
class ServerCall
{
const char *relative_uri;
public:
ServerCall(const char *relative_uri);
RetType doCall();
};
The building logic should be implemented in each derived class. I thought of adding a static_assert
stating that the template argument must be a derived class of a ServerObject
class, and trying to force derived classes of ServerObject
to allow construction based on a JSON message, but I can't figure out a way to do that.
- I can't force a specific constructor signature on a derived class, so the compiler can't be sure that the template arguments will have a
RetType(const char *jsonMessage)
constructor. - I can't have static pure virtual methods, so derived classes can't be forced to implement a
static ServerObject *buildFromJson(const char *jsonMessage)
method and have the compiler choose which method to call based on the template type. - Another idea I had was to use something I do in Java. Declare a
private final
data member in the base class, that is only initialized in the base class constructor, so derived classes are forced to call the base constructor to initialize the data member. And then the base constructor would call abstract methods implemented in the derived class.
But I don't think that works in C++. Even if I could force derived class constructors to call the base class constructor (which doesn't seem possible), base class constructors can't call pure virtual methods.
I have no other ideas. Is there a good way of constructing an object of a template type from a JSON string in C++?