c++ lambda表达式帮助
c++ lambda expression help
我对c++0x有点陌生,谁能给我解释一下为什么下面的编译失败:
void memory_leak_report()
{
std::cout.flags(std::ios::showbase);
std::for_each(allocation_records.begin(), allocation_records.end(),
[] (const struct memory_leak_report& rec) {
std::cout << "memory leak at: " << rec.file << ": line " << rec.line
<< std::hex << ", address: " << rec.address << std::dec
<< ", size:" << rec.size << std::endl;
});
}
std::list<struct memory_allocation_record> allocation_records
和memory_allocation_record
是一个简单的C风格数据结构。
struct memory_allocation_record {
const char *func;
const char *file;
unsigned int line;
unsigned int size;
unsigned long address;
};
我试过编译它:g++ -Wall -g -o alloc main.cpp -std=c++0x
我得到的错误是:在函数中,std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_List_iterator, _Funct = memory_leak_report()::]
错误:没有匹配调用(memory_leak_report()::) (memory_allocation_record&)
注意:候选对象是:void (*)(const memory_leak_report()::memory_leak_report&)
首先,在c++中,你不需要(通常被认为是糟糕的风格)把struct
放在结构体的使用前面。只要const memory_leak_report&
就可以了。
第二,你告诉我们结构体memory_allocation_record
是如何定义的,但是lambda接受memory_leak_report
作为它的参数,据我所知,是一个函数。这是你的错误吗?是应该采取一个memory_allocation_record
代替?
这就引出了最后一点。如果出现错误,你不觉得应该告诉我们错误是什么吗?否则,我们必须猜测我们认为可能是代码中的问题。
编辑
好吧,正如我所料,这似乎就是问题所在。我建议实际阅读编译器的错误。这就是他们在那里的原因。;)
取错误的第一行:
/usr/include/c++/4.5/bits/stl_algo.h:4185:2: error: no match for call to ג(memory_leak_report()::<lambda(const memory_leak_report()::memory_leak_report&)>) (memory_allocation_record&)
去掉不相关的位:
no match for call to <somethingwithlambdas> (memory_allocation_record&)
现在,因为这是一个lambda,类型有点复杂,但最终,它讨论的是一个函数调用,所以最后一个括号描述了参数。换句话说,它试图调用一个以memory_allocation_record&
作为参数的函数,但无法找到匹配的函数。
candidates are: void (*)(const memory_leak_report()::memory_leak_report&) <conversion>
因此,它实际上找到的候选以const memory_leak_report&
作为其参数
现在你只需要比较这两个。当编译器试图将memory_allocation_record&
传递给期望const memory_leak_report&
的函数时,这意味着什么?
- (C++)分析树以计算返回错误值的简单算术表达式
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 需要帮助设置在C++中使用的Potrace
- 提升精神:解析布尔表达式并简化为规范范式
- 在指针的帮助下,文本文件中单词的频率
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用正则表达式regex_search在字符串中查找字符串
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 概念中的cv限定符需要表达式参数列表
- 为什么constexpr的性能比正常表达式差
- 对于结构,表达式必须是可修改的ivalue
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 有人可以帮助我处理正则表达式吗?
- 需要帮助生成C++深度有限的随机表达式树
- 是“警告 C4127”(条件表达式是常量)曾经有帮助
- 需要帮助构建正则表达式模式
- c++ lambda表达式帮助
- 帮助使用正则表达式
- 帮助提升::正则表达式修剪