1

所以我有以下两个类:

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. 这样,我可以使用类似于以下的语法创建非抽象类:

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-derived 类来验证其State-derived 模板参数类实际上是派生自State

4

2 回答 2

1

这符合你的需要吗?

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

添加现场演示

于 2016-01-14T06:19:06.430 回答
1

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 ...
};
于 2016-01-14T09:26:41.247 回答