首页 > 解决方案 > function template with unused template parameter

问题描述

template<typename T>
struct a 
{ 
  using type = int;
  typename T::type i;
};

template<typename T, typename = a<T>>
void f1(T) {}

template<typename T, typename = typename a<T>::type>
void f2(T) {}

int main()
{
  f1<int>(1); // ok
  f2<int>(1); // error

  return 0;
}

An instantiation of a<int> should be an error because int::type is illegal. But it seems that f1<int> can't cause the instantiation of a<T>, but f2<int> can. What's the reason?

标签: c++templatesinstantiationimplicit-instantiation

解决方案


当 type 用作模板参数时(包括默认模板参数),它不需要是完整类型。

类型模板形参的模板实参必须是 type-id,它可以命名不完整的类型:

因此,对于f1,默认模板参数是a<T>并且它不必是完整的。Givenf1<int>(1); a<int>不需要实例化。

但是当你引用类模板的成员时,作为的默认模板参数,typename a<T>::type必须是完整类型,然后导致隐式实例化f2a<T>

当代码在上下文中引用需要完全定义类型的模板时,或者当类型的完整性影响到代码时,并且该特定类型没有被显式实例化时,就会发生隐式实例化。例如,当构造此类型的对象时,而不是构造指向此类型的指针时。

这适用于类模板的成员:除非该成员在程序中使用,否则它不会被实例化,并且不需要定义。

所以给定f2<int>(1);,a<int>会被实例化然后导致编译错误。


推荐阅读