模板参数扣除使用元组在lambda上失败
Template argument deduction fails on lambda using tuple
我正在尝试制作一个查询函数,使我可以查询一个stl容器以了解某些元素特征,然后返回结果集。实际上,这只是正常stl操作周围的句法糖(特别是copy_if和back_inserter)。
#include <string>
#include <tuple>
#include <functional>
#include <vector>
// This is the query function, it compiles fine
template<typename T, typename ... U>
T query(T const& input, std::function<bool(std::tuple<U...> const& row)> pred)
{
T result;
std::copy_if(std::begin(input), std::end(input), std::back_inserter(result), pred);
return result;
}
// Define my Row, with each column having a type
using Row = std::tuple<int, float, std::string>;
int main()
{
// Create a sample vector of Rows
std::vector<Row> vec;
for(size_t i = 0; i < 100; ++i)
vec.emplace_back(i, 5.0f, "hello");
// This is how I would perform the query
// **** This is the line that doesn't compile due to template arg deduction failure ****
auto result = query(vec, [](Row const& row) -> bool { return true; });
return 0;
}
这是编译器输出(Clang 3.3)
main.cpp:27:19: error: no matching function for call to 'query'
auto result = query(vec, [](Row const& row) -> bool { return true; });
^~~~~
main.cpp:8:3: note: candidate template ignored: failed template argument deduction
T query(T const& input, std::function<bool(std::tuple<U...> const& row)> pred)
^
1 error generated.
lambda不是std::function
,它是一种具有重载operator()
的类类型,两种类型是不同的类型。query
函数需要一个std::function<...>
参数,并且模板参数扣除需要类型是确切的匹配(除了CV-Qualifiers之外),因此永远不会将从lambda表达式转换为std::function
的转换。
当然,一个解决方案是在调用query
std::function
auto result = query(vec,
std::function<bool(Row const&)>(
[](Row const&) { return true; }));
另一个选择是更改您的功能本身
template<typename T, typename UnaryPredicate>
T query(T const& input, UnaryPredicate&& pred)
{
T result;
std::copy_if(std::begin(input), std::end(input),
std::back_inserter(result), std::forward<UnaryPredicate>(pred));
return result;
}
现在可以使用您的原始代码来称呼它。
实时演示
相关文章:
- C++:TypeDef使用元组
- Pybind11:将元组列表从Python传递到C++
- 重载元组索引运算符-C++
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将fold表达式与std::一起用于两个元组
- std::ranges::elements_view,用于自定义类似元组的数据
- 将元组的向量转换/构造为堆
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 将元组的向量构造成堆
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 类内部和外部静态 constexpr 元组之间的差异
- 可变参数模板与使用元组在参数中添加不同的数据对
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- boost::包含提升单元的元组的哈希值
- 使用领带从元组中分配 2 个 lambda
- 带有映射的 Lambda 函数,其中键是元组,值是双精度
- 模板参数扣除使用元组在lambda上失败
- 如何通过lambda使用自定义相等来查找在std::vector中具有一个匹配元素的元组