Lamda 仅在声明为"自动"时编译,而不是在声明为'bool'时编译

Lamda only compiles when declared 'auto', not when declared 'bool'

本文关键字:编译 声明 bool Lamda 自动      更新时间:2023-10-16

考虑下面的模板函数sort(...(。这是一个围绕 std::sort 的包装函数。目的是在对用户定义类的向量进行排序时提供更好的语法。第一个参数是要排序的向量。第二个参数是一个函数,指定向量如何排序(在哪个公共成员变量或函数上(。

std::sort 需要一个比较函数来对向量中的不同项目进行排名。这在我的排序函数中被声明为一个 lambda。但是,此代码仅在 lambda 声明为"auto"时才编译,而不是在声明为 bool 时编译。我觉得这很奇怪。有人可以解释一下吗?

(代码应该按现在的样子编译。要观察问题,请取消注释以"bool"开头的行(。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Copy function is needed in sort(...), below
template<typename T>
auto copy(const std::vector<T>& v)
{
auto r = std::vector<T>();
r.reserve(v.size());
for(const auto & e : v) {
r.push_back(e);
}
return std::move(r);
}
template<typename T, typename F>
auto sort(const std::vector<T>& v, const F& f)
{
auto r = copy(v);
// ///////////// Consider the following line: /////////////////
// bool compare = [=](const T& lhs, const T& rhs)               // does not compile, why?
// auto compare = [=](const T& lhs, const T& rhs) -> bool    // compiles
auto compare = [=](const T& lhs, const T& rhs)            // compiles
{
return f(lhs) < f(rhs);
};
std::sort(r.begin(), r.end(), compare);
return std::move(r);
}
struct Foo {
int id;
string message;
};
int main()
{
auto unordered = vector<Foo>();
unordered.push_back(Foo{2, "the last element"});
unordered.push_back(Foo{1, "the first element"});
// I want to sort the vector by 'id'.
auto ordered = sort(unordered, [](const auto& e) { return e.id; }); 
cout << "Ordered vector (by id):" << endl;
for(const auto& e : ordered) {
cout << e.id << ", " << e.message << endl;
}
return 0;
}

lambda 的类型是实现定义的。因此,如果您要声明一个变量来保存 lambda,它必须始终为auto类型。您似乎将 lambda 的返回类型与实际保存 lambda 本身的变量的类型混淆了。

// variable type | variable identifier | lambda expression (return type deduced)
bool            compare             = [=](const T& lhs, const T& rhs)
// variable type | variable identifier | lambda expression              | return type
auto            compare             = [=](const T& lhs, const T& rhs) -> bool  
// variable type | variable identifier | lambda expression (return type deduced)
auto            compare             = [=](const T& lhs, const T& rhs) 

上表说明了声明的每一部分所涉及的内容。在你的代码中,compare是一个lamda。如果你声明一个类型为bool的变量,然后尝试为其分配一个 lamda,你将不可避免地得到编译器错误。