承担一个功能以接受支撑初始器列表,而无需其他Overload

问题描述 投票:0回答:1

它以通用方式使用基于范围的forops对其进行操作。

这与标准容器,C风格数组和
std::generator

iterate({1, 2, 3});

一起工作正常,但是当我尝试将其传递给Init-list时,它会失败:

error: no matching function for call to ‘iterate(<brace-enclosed initializer list>)

我得到错误

couldn’t deduce template parameter ‘auto:57

std::span

如何在考虑的候选人中包含iNtalizer列表,而无需编写单独的超负荷?我只需要一个功能,因为我也想编写基于迭代器的实用程序,该实用程序在多个迭代元素上运行,而且如果我必须为所有这些功能编写功能,如果我不得不为它们编写多个功能,以便在所有迭代中运作。普通迭代和启动列表的每种组合。
    
在C ++ 20及以后,您的最佳选择是通过将其传递给您的现有函数的过载来添加一个过载,例如:

template <class T> auto iterate (std::initializer_list <T> il) { std::span s {il.begin (), il.end ()}; return iterate (s); }

c++ iterator initializer-list c++23
1个回答
0
投票
span

便宜的构建价格(在这种情况下甚至可能是免费的),所以我看不到不利的一面。

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.