根据模板的基本类型创建不同的模板class

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

我将尝试用一个简单的例子来解释我的问题:

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

总而言之,如果 T 模板派生自 Runnable class,我希望使用 class Task : public RUNNABLE class。如果模板 TRun 类型,我希望使用 class Task<Run> class,在所有其他情况下,程序不必编译。

我该怎么办?

您可能 static_assert 您的条件(具有特征 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