模板参数中模板参数个数错误

Template template parameter with wrong number of template parameters

本文关键字:参数 错误      更新时间:2023-10-16

考虑一个模板类C,其策略集通过模板模板参数和两个策略定义:

template<class T> struct PolicyOne { };
template<class T, int U, int V> struct PolicyTwo { };
template<class T, template<class> class POLICY> struct C { POLICY<T> policy; };
void f()
{
    C<int, PolicyOne> mc1;
    C<int, PolicyTwo<1, 2> > mc2; // doesn't work this way
}

PolicyTwo不能工作,因为模板参数的数量错误。是否有一种方法来使用PolicyTwo作为POLICY模板参数,如果你指定类型的附加模板参数?

我使用c++ 03,所以别名声明是不可用的。我知道这个问题,但我没有看到解决我的问题的办法。

根据策略的使用方式,您可以使用继承来代替别名模板进行管理:

template<int U, int V> struct PolicyTwoAdaptor {
  template<class T> struct type: PolicyTwo<T, U, V> { }; };
C<int, PolicyTwoAdaptor<1, 2>::type> mc2;

我看不出有谁可以用你目前的机制来解决这个问题,但是你可以逆转它的工作方式,它应该可以很好地编译(甚至可以通过删除类模板参数来降低复杂性):

template <typename T> struct PolicyBase { typedef T value_type; };
template<class T> struct PolicyOne : public PolicyBase<T> { };
template<class T, int U, int V> struct PolicyTwo : public PolicyBase<T> { };
template<class POLICY> struct C { POLICY policy; typedef typename POLICY::value_type T; };
void f()
{
    C<PolicyOne<int> > mc1;
    C<PolicyTwo<int, 1, 2> > mc2; // doesn't work this way
}

基本思想是将类型模板参数移出策略用户,并为其提供完全实例化的策略。然后,策略通过typedef(如果需要)向策略用户提供其模板类型。