C++ 使用初始值设定项列表将模板大小的数组传递给函数
我有一个模板函数,它以任意大小的C++ 使用初始值设定项列表将模板大小的数组传递给函数,c++,templates,initializer-list,C++,Templates,Initializer List,我有一个模板函数,它以任意大小的std::array作为参数。大致如下: template <size_t n> void foo(const std::array<int, n>& numbers) { for (const auto & number: numbers) { // ... do stuff ... } } 给我以下错误: error: no matching member function for ca
std::array
作为参数。大致如下:
template <size_t n>
void foo(const std::array<int, n>& numbers) {
for (const auto & number: numbers) {
// ... do stuff ...
}
}
给我以下错误:
error: no matching member function for call to 'foo'
note: candidate template ignored: couldn't infer template argument 'n'
错误:调用“foo”时没有匹配的成员函数
注意:已忽略候选模板:无法推断模板参数“n”
有没有办法让我的函数使用初始化列表或类似的东西工作
{/*..*/}
没有类型,因此除了std::initializer_list
和C数组T(&a)[N]
之外,无法在模板函数中推导
所以你必须
- 添加重载以处理
或C数组std::initializer\u list
// span (C++20) has constructor from std::array :) void foo(const std::span<int>& numbers) { for (const auto & number: numbers) { // ... do stuff ... } } void foo(std::initializer_list<int> numbers) { foo(std::span{numbers.begin(), numbers.size()}); }
//span(C++20)具有来自std::array的构造函数:) void foo(const std::span和number){ 用于(常量自动和编号:编号){ //…做事。。。 } } void foo(标准::初始值设定项\u列表编号){ foo(std::span{numbers.begin(),numbers.size()}); }
- 或者提供非推断模板参数:
foo({4,5})代码>
- 或者为
提供类型(使用C++17的CTAD更容易):{}
foo(std::array{4,5})代码>
void foo(std::initializer\u列表编号)
?除了foo({4,5})代码>也可以。是的,很难看,但可能更糟。@Jarod42那么我不能再通过已经存在的阵列了,是吗?@ypnos啊,是的,这很有效……谢谢。但是,如果不专门化模板,为什么这项工作不起作用呢?std::span
非常棒,但请注意,它是在C++20中引入的(不会从答案中删除,以防有人想尝试代码示例)。@ypnos:事实上,我使用了span
来避免重复代码。在以前的标准中,我们可能使用版本获取2个迭代器或重新实现span
。
error: no matching member function for call to 'foo'
note: candidate template ignored: couldn't infer template argument 'n'
// span (C++20) has constructor from std::array :)
void foo(const std::span<int>& numbers) {
for (const auto & number: numbers) {
// ... do stuff ...
}
}
void foo(std::initializer_list<int> numbers) {
foo(std::span{numbers.begin(), numbers.size()});
}