Search code examples
c++templates

C++ declare pure virtual template function must support certain types


Lets say I declare a pure virtual method called readPrimitive

template<class T> void readPrimitive(string data, T& out) = 0;

And I want to specify that derived classes who give this method an implementation MUST support a handful specific types (in my example, all primitive types such as short, long etc.)

How do I do that?


Solution

  • As a set of non-template overloads of those specific types:

    virtual void readPrimitive(string data, int& out) = 0;
    virtual void readPrimitive(string data, float& out) = 0;
    virtual void readPrimitive(string data, string& out) = 0;
    

    Virtual functions cannot be templates anyway.