c++ - 无法推断模板参数 'N'

标签 c++ templates c++14 stdarray template-argument-deduction

我试图将其减少到最低限度:

#include <array>

template <std::size_t N>
void f(int, std::array<int, N> const & =
       std::array<int, 0>()) {
}


int main() {
    f(10);
}

array_test.cpp:4:6: 注意:模板参数推导/替换失败: array_test.cpp:10:9: 注意:无法推断模板参数“N” f(10);

为什么会失败?我不明白:它应该可以从默认参数中推导出来。我需要一个解决方法。

最佳答案

你需要给N一个默认值,而不是数组:

template <std::size_t N = 0>
void f(int, std::array<int, N> const & =
       std::array<int, N>()) {

}

至于为什么不能从默认值推导出N,参见Why can't the compiler deduce the template type from default arguments? .

关于c++ - 无法推断模板参数 'N',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41587485/

相关文章:

c++ - 存储 strtok() token 的值?

php - 自定义帖子类型WordPress模板如何在WordPress模板中添加自定义侧边栏

c++ - 奇怪的重复模板模式 - 不能创建超过 1 个派生类?

c++ - 为什么类型在自动和模板函数情况下都没有推导为 `const` 类型?

c++ - 我们应该在 lambda 中通过 const 引用捕获吗?

numpy - xt::where 用于 xtensor C++ 的示例用法

c++ - 使用 execv 执行基本 I/O

c++ - 智能指针与初始值设定项列表混淆

c++ - 尝试在C++主函数内更改全局变量值时出现编译错误

c++ - 以 pair 为键的 map (vs) unordered_map