温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c++ - Create different template class according to the basic type of the template
c++ inheritance templates type-constraints template-inheritance

c++ - 根据模板的基本类型创建不同的模板类

发布于 2020-03-28 23:35:27

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

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

我能怎么做?

查看更多

查看更多

提问者
Parmi93
被浏览
31
Jarod42 2020-01-31 18:11

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

    // ...
};

演示版