Force template parameter class to inherit from another templated class with partially fulfilled parameters

后端 未结 2 1959
無奈伤痛
無奈伤痛 2021-01-23 09:04

So I have the following two classes:

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

template < class Trans         


        
相关标签:
2条回答
  • 2021-01-23 09:37

    With

    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*>()));
    

    You may do

    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 ...
    };
    
    0 讨论(0)
  • 2021-01-23 09:52

    Does this suit your need?

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

    ADDED: Live Demo

    0 讨论(0)
提交回复
热议问题