Deduce std :: array size?(Deduce std::array size?)

在以下代码中:

template<size_t N> int b(int q, const std::array<int, N>& types) { int r = q; for (int t : types) { r = r + t; } return r; } int main() { b<2>(9, { 2,3 }); }

如何避免在为N调用b时指定2? 为什么不能自动推断出这种类型呢? 有了它我得到错误:

'b':找不到匹配的重载函数'int b(int,const std :: array&)':无法推导'N'的模板参数

In the following code:

template<size_t N> int b(int q, const std::array<int, N>& types) { int r = q; for (int t : types) { r = r + t; } return r; } int main() { b<2>(9, { 2,3 }); }

How can I avoid having to specify 2 in the call to b for N? Why can't this type be automatically deduced? With out it I get the error:

'b': no matching overloaded function found 'int b(int,const std::array &)': could not deduce template argument for 'N'

最满意答案

模板参数推导依赖于实际参数和形式参数之间的直接类型匹配。 实际参数是初始化列表。 它与array类型不匹配(最多可以匹配std::array中的内部原始std::array ,但语言规则不支持)。

相反,您可以使用原始数组,即:

#include <stddef.h> #include <array> template<size_t N> int b(int q, int const (&types)[N] ) { int r = q; for (int t : types) { r = r + t; } return r; } int main() { b( 9, { 2, 3 } ); }

或者,如果在编译时不是绝对需要N ,则可以使用std::initializer_list 。

还有许多其他可能相关的方法(例如可变参数模板函数,或定义构建std::vector的运算符),但很难说什么适合您未公开的目的。

Template argument deduction relies on direct type matching between actual argument and formal argument. The actual argument is an initializer list. It doesn't match the array type (at best it could match the internal raw array in a std::array, but the language rules don't support that).

Instead you can just use a raw array, to wit:

#include <stddef.h> #include <array> template<size_t N> int b(int q, int const (&types)[N] ) { int r = q; for (int t : types) { r = r + t; } return r; } int main() { b( 9, { 2, 3 } ); }

Or, if you don't absolutely need N at compile time, you can use a std::initializer_list.

There are also many other possibly relevant approaches (e.g. variadic template function, or defining an operator to build up a std::vector), but it's difficult to say what would suit your undisclosed purpose.

更多推荐