将显式实例化的函数模板与转换匹配
Matching explicitly instantiated function template with conversion
考虑这个带有隐式构造函数的模板
template<typename T>
struct X { X(T) { } };
和这个函数模板
template<typename T>
void func(X<T>) { }
即使我为 T = int
显式实例化 func<T>()
template void func<int>(X<int>);
像这样调用 func
不会编译
func(1);
错误:
no matching function call for 'func'
我知道模板参数推导不适用于转换,但在这种情况下,我创建了 func
的显式实例化,因此不需要推导,我希望转换与普通函数一样工作。
为什么不起作用?
问题给出func(1);
,template argument deduction推导失败T
(如int
)。
In order to instantiate a function template, every template argument must be known
但是
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
显式实例化没有任何改变;模板参数推导无法推导 T
,那么不会发生(func<int>
或其他实例化)。
您可以明确指定模板参数以绕过模板参数推导。
func<int>(1);
你可以像这样为它写一个包装器
template<typename T>
void bar(T t) {
func<T>(t);
}
那么你可以
bar(1);
考虑这个带有隐式构造函数的模板
template<typename T>
struct X { X(T) { } };
和这个函数模板
template<typename T>
void func(X<T>) { }
即使我为 T = int
func<T>()
template void func<int>(X<int>);
像这样调用 func
不会编译
func(1);
错误:
no matching function call for 'func'
我知道模板参数推导不适用于转换,但在这种情况下,我创建了 func
的显式实例化,因此不需要推导,我希望转换与普通函数一样工作。
为什么不起作用?
问题给出func(1);
,template argument deduction推导失败T
(如int
)。
In order to instantiate a function template, every template argument must be known
但是
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
显式实例化没有任何改变;模板参数推导无法推导 T
,那么不会发生(func<int>
或其他实例化)。
您可以明确指定模板参数以绕过模板参数推导。
func<int>(1);
你可以像这样为它写一个包装器
template<typename T>
void bar(T t) {
func<T>(t);
}
那么你可以
bar(1);