最小化的示例:
template <typename T, int N>
struct Deducer {
Deducer(int) {}
};
template <typename T, int N = 1>
void foo(Deducer<T, N> d){}
int main() {
foo<char>(345);
}
godbolt example
屈服误差
candidate template ignored: could not match 'Deducer<char, N>' against 'int'
为什么编译器会忽略隐式强制转换?
如果这里有任何简单的解决方法?
我可以考虑以下两种选择:
(1)指定所有模板参数(对我来说不是一个选项,实际情况下有很多,我想推论)
(2)编写这样的中间函数:
template <typename T, int N = 1>
void foo_step(int d){ foo<T, N>(d); }
也没有选择,我有很多论点。
有任何想法吗?
最佳答案
根据this:
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
您可以尝试使用以下方法:
template <typename T, typename U, int N = 1>
void foo(U&& u)
{
foo(Deducer<T,N>(std::forward<U>(u)));
}
关于c++ - 为什么模板参数推导失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60112272/