0

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++?

devil0150
  • 1,350
  • 3
  • 13
  • 36
  • *"I can't force a specific constructor signature on a derived class"* Why not? What's stopping you? *"I can't have static pure virtual methods"* It doesn't need to be virtual, just a plain static member function would do. – Igor Tandetnik Dec 28 '17 at 04:50
  • I looked but I couldn't find a way to force a specific constructor signature on all derived classes of a base class. If I create a normal static member function that doesn't exist in the base class, the compiler wouldn't know to call it from a template argument. (since it only knows the methods from the base class) – devil0150 Dec 28 '17 at 12:08

0 Answers0