强制模板参数类继承自具有部分实现的参数的另一个模板类 [英] Force template parameter class to inherit from another templated class with partially fulfilled parameters

查看:153
本文介绍了强制模板参数类继承自具有部分实现的参数的另一个模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下两个类:

template < class Cost >
class Transformation {
  public:
    virtual Cost getCost() = 0;
};

template < class TransfCl, class Cost >
class State {
    protected:
        State(){
            static_assert(
                std::is_base_of< Transformation< Cost >, TransfCl >::value,
                "TransfCl class in State must be derived from Transformation< Cost >"
            );
        }
    public:
        virtual void apply( const TransfCl& ) = 0;
};

但是希望能够删除 code>的模板参数 State ,因为 State 的功能完全独立于 Cost 。这样,我可以使用类似于下面的语法创建非抽象类:

But would like to, instead, be able to drop the Cost template parameter to State, because State's functionality is completely independent of Cost. This way, I could create non-abstract classes using a syntax similar to this:

class TransfImpl : public Transformation< int >{
    public: int getCost(){ return 0; }
};

class StateImpl : public State< TransfImpl >{
    public:
        StateImpl(){
            static_assert(
                std::is_base_of< Transformation, TransfImpl  >::value,
                "TransfImpl must inherit from Transformation< Cost >"
            );
        }
        void apply( const TransfImpl & ){}
};

我也希望最终将这个链接到第三个类,它将使用 State -derived类作为其模板参数,但不需要也具有 Transformation -derived和 Cost - 来自模板参数,以验证其 State - 来自模板参数类实际上是从状态

I also wanted to eventually chain this to a third class, which would use the State-derived class as its template parameter, but wouldn't need to also have the Transformation-derived and Cost-derived classes in its template parameters to verify that its State-derived template parameter class is, in fact, derived from State

推荐答案

使用

template <template <typename...> class C, typename...Ts>
std::true_type is_template_base_of_impl(const C<Ts...>*);

template <template <typename...> class C>
std::false_type is_template_base_of_impl(...);

template <template <typename...> class C, typename T>
using is_template_base_of = decltype(is_template_base_of_impl<C>(std::declval<T*>()));

您可以执行

template <class TransfCl>
class State {
protected:
    static_assert(is_template_base_of<Transformation, TransfCl>::value,
                  "TransfCl class in State must be derived from Transformation<Cost>");

    // previous code ...
};

这篇关于强制模板参数类继承自具有部分实现的参数的另一个模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆