【发布时间】:2017-12-26 17:59:54
【问题描述】:
C++17 引入了class template argument deduction。虽然大多数时候它只不过是一种语法糖,但在某些情况下它确实能起到拯救作用,尤其是在泛型代码中,例如 in this case。
此功能的另一个不错的应用是std::array 的用法。确实,现在它引起的痛苦少了很多,只需比较这两个版本:
std::array arr{ 1, 2, 3, 4, 5 }; // with C++17 template argument deduction
std::array<int, 5> arr{ 1, 2, 3, 4, 5 }; // just a normal C++11 std::array
确实,一旦我决定再添加一个元素,我就可以在不明确将类型更改为 std::array<int, 6> 的情况下完成它。
但是,以下内容无法编译:
std::array arr{ 1, 2, 3.f, 4, 5 };
模板参数推导失败是有道理的,产生如下错误:
main.cpp:7:26: error: class template argument deduction failed:
std::array arr{2,4.,5}; // will not compile
但是,当我尝试给出提示时,它并没有解决问题:
std::array<float> arr{ 1, 2, 3.f, 4, 5 }; // will not compile as well
现在编译器错误消息如下:
main.cpp:7:21: error: wrong number of template arguments (1, should be 2)
std::array<float> arr{2,4.,5};
^
这是为什么呢?为什么我不能只为类提供一些模板参数,但我可以为函数提供?
【问题讨论】:
标签: c++ c++17 stdarray template-argument-deduction