【问题标题】:Create different template class according to the basic type of the template根据模板的基本类型创建不同的模板类
【发布时间】:2020-05-16 23:36:20
【问题描述】:

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

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&lt;Run&gt; 类,并且在所有其他情况下程序不必编译。

我该怎么办?

【问题讨论】:

    标签: c++ templates inheritance type-constraints template-inheritance


    【解决方案1】:

    你可以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

    【讨论】:

    • 好的,很好的解决方案,我稍微修改了最初的问题,使 Runnable 类不抽象。
    • std::is_base_of&lt;Runnable , Runnable &gt;::value 是真的。如果这是您的问题。
    • 但我希望它返回 false
    • 您仍然可以添加和&amp;&amp; !std::is_same&lt;Runnable , RUNNABLE&gt;::value
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多