lundi 5 septembre 2016

Is there an idiom/design pattern for restricting templates?

How do one restrict the typename T to specific type? Consider this:

    template <typename T>
    struct Worker {
        // T can only be certain type allowing specific functionality.
        // i.e T needs to be a product of some interface, support some functions, say T::toString(),  T::print(), T::get().
        //Do soemthing with T 
    };

This is what I usually end up doing.

    struct WorkableType { 
        std::string toString() { return ""; }
        int get() { return 0;}
    }

    struct WorkabelTypeA : WorkableType {
        std::string toString() { return "A"; }
        int get() { return 1;}
    };

    //Similarly
    struct WorkableTypeB : WorkableType;

And use static assert and std::is_base_of

    template <typename T>
    struct Worker {
        static_assert(std::is_base_of<WorkableType, T>::value, "Needs workable type");
        //Do soemthing with T 
    };

Is there any other design pattern, a more c++ way to 'restrict' accidental instantiation of bad typed templates?

Aucun commentaire:

Enregistrer un commentaire