c++ - 为什么模板参数推导失败?

标签 c++

最小化的示例:

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/

相关文章:

c++ - 通过调整场景大小改变 qgraphicsitem 位置

c++ - &(int) { 1 } 在 C++ 中是什么意思?

C++ 与 gcc 和 visual studio 的不同编译错误, 'within this context'

c++ - 如何从一个非常大的数字的 C++ 字符串中提取所有数字?

c++ - 在初始值设定项列表中采用多个参数的成员变量

c++ - 如何在 getline() 中不使用\n 作为分隔符

C++:创建一个全局 ofstream 变量

c++ - 使用字符串流获取行分隔符

c++ - 从 QWidgetList (QList<QWidget*>) 访问 QWidget 子槽/信号

c++ - 在自动var销毁之前或之后创建的C++返回值?