Search code examples
c++templatesoverridingenable-if

Template specialization enable_if


I am trying to specialize a template this way:

class PropertyBase
{
public:
    SfPropertyBase(string name)
    {
        Name = name;
    }

    virtual ~SfPropertyBase() {}

    string Name;

    virtual bool FromString(Object* obj, string str) = 0;

};


template< typename T>
class Property : public SfPropertyBase
{
public:
    Property(string name) : SfPropertyBase(name)
    {
        //specific to Property stuff
    }



    template<typename U = T>
    typename std::enable_if<(std::is_class<U>::value && std::is_pointer<U>::value), bool>::type
    FromString(Object* obj, string str)
    {
        //do something
        return true;
    }

    template<typename U = T>
    typename std::enable_if<!std::is_class<U>::value || !std::is_pointer<U>::value), bool>::type
    FromString(Object* obj, string str)
    {
        //do something
        return true;
    }
}

Then, when I try to initialize an instance of this class:

 auto prop = new Property<int>("IntProperty");

I get invalid new-expression of abstract class type Property<int>. I understand that there is an abstract function in PropertyBase, but I also provide both specializations for Property, where T is a class and where it isn't.

What is going on and how to fix it?

Note: what I want to achieve is to specialize FromString if T is a class/pointer and all the other cases.


Solution

  • Both the FromString in Property are function template, they can't override the non-template virtual function of the base class. (In fact functions templates cannot be virtual functions).

    You could add another non-template FromString in Property; and you can ensure the overriding by using the keyword orverride. e.g.

    bool FromString(Object* obj, string str) override {
        return FromString<>(obj, str);
    }
    

    LIVE