Lamda 仅在声明为"自动"时编译,而不是在声明为'bool'时编译
Lamda only compiles when declared 'auto', not when declared 'bool'
考虑下面的模板函数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,你将不可避免地得到编译器错误。
相关文章:
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 未声明的标识符编译暗黑破坏神 2 程序"muleview"
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 即使不包含其标头,如何成功向前声明的类编译?
- 如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- Lamda 仅在声明为"自动"时编译,而不是在声明为'bool'时编译
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- C++ SPDLOG 编译错误:变量或字段"set_error_handler"声明为无效
- 在 mingw64- 变量下的窗口中编译 openvpn3 时出错,未在范围内声明
- 尝试编译GoogleTest,但出现以下错误:尚未声明'::OpenThread'
- 如何实现声明功能-C 11,编译时间
- 可变参数模板仅在正向声明时编译
- std::d eclare_if 或其他在编译时丢弃成员声明的假设方法
- 编译错误 在 C++ 上,Calcarea 未在此范围内声明
- 试图过渡到GTK3(针对GTK -3.0库编译)时,在此范围内未声明GTK_Object
- 如何为 std::array 声明全局编译时常量?
- 我的Qt程序可以编译,但是当我在声明中使用ifstream时崩溃
- 代码块编译错误.Cin 未在此范围内声明