Template template parameter with wrong number of t

2020-07-16 08:25发布

Consider a template class C with a policy set via template template parameter and two policy definitions:

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 doesn't work because of wrong number of template arguments. Is there a way to use PolicyTwo as POLICY template parameter if you specify the types for the additional template parameters?

I'm using C++03, so alias declarations are not available. I'm aware of this question, but I don't see a solution to my problem there.

标签: c++ templates
2条回答
啃猪蹄的小仙女
2楼-- · 2020-07-16 08:40

Depending on how the policy is used, you may be able to manage with inheritance in place of alias templates:

template<int U, int V> struct PolicyTwoAdaptor {
  template<class T> struct type: PolicyTwo<T, U, V> { }; };
C<int, PolicyTwoAdaptor<1, 2>::type> mc2;
查看更多
霸刀☆藐视天下
3楼-- · 2020-07-16 08:46

I can't see hwo to solve this with your current mechanism, but you can reverse the way it works and it should compile fine (and even may reduce complexity by removing the class template parameter):

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
}

The basic idea is to move the type tempalte parameter out of the policy user, and give a fully instantiated policy to it instead. Then the policy provides its template type back to the policy user through a typedef (if needed).

查看更多
登录 后发表回答