vendredi 30 mars 2018

How to elegantly check if the template type is derived from the specific base class in C++11?

I have a template class Context. I want to limit the user to use the specified type (Stratege1 but not Stratege2) that is derived from a specific class Base.

class Base {
public: 
    virtual void run() = 0;
}; 
class Stratege1 : public Base {
public:
    virtual void run() {
        printf("Stratege1 \n");
    }
}; 
class Stratege2 {
public:
    virtual void run() {
        printf("Stratege2 \n"); 
    }
}; 
template <typename T> class Context {
public:
    void run() { 
        t.run();
    }; 
private:
    T t;
};

It may be OK if the user want to invoke like this:

Context<Stratege1> context;
context.run();

However I don't expect the user use (to avoid unexpectedly potential run-time issues)

Context<Stratege2> context;
context.run();

Because Stratege2 is not derived from Base class. Is there any elegant way to limit the concept during compilation?

Thanks for any suggestions.

Aucun commentaire:

Enregistrer un commentaire