c++templatesinheritancetype-constraintstemplate-inheritance

Create different template class according to the basic type of the template


I will try to explain my problem with a simple example:

class Runnable
{
protected:
    virtual bool Run() { return true; };
};

class MyRunnable : Runnable
{
protected:
    bool Run()
    {
        //...
        return true;
    }
};

class NotRunnable
{ };

class FakeRunnable
{
protected:
    bool Run()
    {
        //...
        return true;
    }
};
//RUNNABLE must derive from Runnable
template<class RUNNABLE>
class Task : public RUNNABLE
{
public:
    template<class ...Args>
    Task(Args... args) : RUNNABLE(forward<Args>(args)...)
    { }

    void Start()
    {
        if(Run()) { //... }
    }
};
typedef function<bool()> Run;

template<>
class Task<Run>
{
public:
    Task(Run run) : run(run)
    { }

    void Start()
    {
        if(run()) { //... }
    }

private:
    Run run;
};

main.cpp

Task<MyRunnable>();                //OK: compile
Task<Run>([]() { return true; });  //OK: compile
Task<NotRunnable>();               //OK: not compile
Task<FakeRunnable>();              //Wrong: because compile
Task<Runnable>();                  //Wrong: because compile

In summary, if the T template derive from the Runnable class, I want the class Task : public RUNNABLE class to be used. If the template T is of the Run type I want the class Task<Run> class to be used, and in all other cases the program does not have to compile.

How can I do?


Solution

  • You might static_assert your condition (with traits std::is_base_of):

    template<class RUNNABLE>
    class Task : public RUNNABLE
    {
    public:
        static_assert(std::is_base_of<Runnable, RUNNABLE>::value
                      && !std::is_same<Runnable , RUNNABLE>::value);
    
        // ...
    };
    

    Demo