c – 具有未使用模板参数的函数模板
作者:互联网
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;
}
< int>的实例化应该是一个错误,因为int :: type是非法的.但似乎f1< int>不能导致< T>的实例化,但是f2< int>能够.什么原因?
解决方法:
当type用作template argument(包括默认模板参数)时,不需要是完整类型.
A template argument for a type template parameter must be a type-id, which may name an incomplete type:
因此对于f1,默认模板参数是< T>.它不必是完整的.给定f1< int>(1);一个< INT>不需要实例化.
但是当你引用类模板的成员时,作为默认模板参数typename a< T> :: f2的类型,< T>必须是完整的类型,然后导致implicit instantiation.
When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.
This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition.
因此,给定f2< int>(1);,< int>将被实例化,然后导致编译错误.
标签:c,templates,instantiation,implicit-instantiation 来源: https://codeday.me/bug/20190910/1800361.html