使用类模板而不传递模板参数

时间:2013-05-20 13:51:18

标签: c++ templates

// p1: some value
// nt: native type
template<int p1, typename nt>
struct A {};

// pt: pointer to type i.e. int*
// tA: a specialization of A
template<typename pt, typename tA>
struct B1 {};

// pt: pointer to type i.e. int*
// tA: a specialization of A
template<typename pt, typename tA>
struct B2 {};

// tB: specialization of B?
// tA: specialization of A
template<typename tB, typename tA>
struct C {};

// now i want to create a C partial specialization where:
//  A<some_value, native_type>
//  B?<char*, A<some_value, native_type> >

template< template<typename, typename> class B, int p1, typename nt >
struct C< B<char*, A<p1, nt> >, A<p1, nt> > {};

int main()
{
    C< B1, A<10, int> > c;
}

用clang编译上面的代码时会出错:

error: use of class template B1 requires template arguments
   C< B1, A<10, int> > c;
      ^~

我理解错误并修复它B1应为B1<char*, A<10, int> >。编译器是否应从最匹配的专业化中扣除这些参数的值?

1 个答案:

答案 0 :(得分:4)

  

编译器是否应从最匹配的专业化中扣除这些参数的值?

我不确定我理解你的问题,但如果我这样做,那么答案就是“不”。编译器不知道如何从类模板(B1的裸名称)中推导出完全实例化的类型(在本例中为B1的特化)。您必须为B1指定模板参数。

请记住,在为主模板提供必要的参数后,将选择主模板的特化。在这种情况下,您的主模板接受两个类型参数,您必须提供两个类型参数。

您在模板专精中使用模板模板参数B以匹配B实例的类型参数这一事实并未改变主模板参数的事实是两个(完全实例化的)类型