c++ - 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?
解决方案
当 type 用作模板参数时(包括默认模板参数),它不需要是完整类型。
类型模板形参的模板实参必须是 type-id,它可以命名不完整的类型:
因此,对于f1
,默认模板参数是a<T>
并且它不必是完整的。Givenf1<int>(1);
a<int>
不需要实例化。
但是当你引用类模板的成员时,作为的默认模板参数,typename a<T>::type
必须是完整类型,然后导致隐式实例化。f2
a<T>
当代码在上下文中引用需要完全定义类型的模板时,或者当类型的完整性影响到代码时,并且该特定类型没有被显式实例化时,就会发生隐式实例化。例如,当构造此类型的对象时,而不是构造指向此类型的指针时。
这适用于类模板的成员:除非该成员在程序中使用,否则它不会被实例化,并且不需要定义。
所以给定f2<int>(1);
,a<int>
会被实例化然后导致编译错误。
推荐阅读
- laravel - 安装 Laravel Valet 时的问题
- excel - 如何使用 excel VBA/宏在网格中填充数组公式(使用多个条件)?
- django - django heroku 部署 postgres 配置
- c# - 字符之一匹配的断行
- linux - 为什么我在ansible中看到remote_user应该是字符串错误?
- java - Println 正在插入我不想要的额外行,“2 个换行符而不是 1 个”
- hybris - 斯巴达克斯店面设置问题
- jasper-reports - Detail Band 溢出到下一页并导致第二个列表被下推太多
- python - 使用 numpy 和 swig 将二维数组作为参数传递给函数
- html - CSS Flexbox - 为什么我的图像重叠?