强制模板参数 class 继承自另一个具有部分实现参数的模板化 class

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

所以我有以下两个classes:

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

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

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 & ){}
};

我还想最终将它链接到第三个 class,它将使用 State 派生的 class 作为其模板参数,但不需要也有Transformation-derived 和 Cost-derived classes 在其模板参数中验证其 State-derived 模板参数 class 实际上是派生的来自 State

这符合您的需要吗?

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 & ){}
};

已添加Live Demo

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