0

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

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;
};

主文件

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 Task : public RUNNABLE该类。如果模板TRun我希望使用的class Task<Run>类的类型,并且在所有其他情况下,程序不必编译。

我能怎么做?

4

1 回答 1

2

您可能会遇到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);

    // ...
};

演示

于 2020-01-31T09:55:19.893 回答