Ale*_*ang 0 c++ algorithm lambda unique-ptr c++11
当我尝试使用for_each算法时,我遇到以下错误std::unique_ptr.我在下面的profile.h部分放大了它.
奇怪的是,如果我将其更改为能够编译std::shared_ptr,我怀疑它是按值获取容器的元素,因此不喜欢对unique_ptrs的引用.但是,我希望它unique_ptr理想情况下,因为这些任务应该放在ToRun_容器内,并Completed_在任务执行后移动到容器,所以shared_ptr这里没有任何好处.
我得到的错误是:
调用类型为'的对象没有匹配函数(Lambda at Profile.cpp:429:54)'
__f(*__第一);
这是指这行代码:
for_each(ToRun_.begin(), ToRun_.end(), [&os](std::unique_ptr<Task>& e){
if (e){
os << e->getName() <<'\n';
}
});
Run Code Online (Sandbox Code Playgroud)
在我将其转换为使用智能指针之前,我使用了原始指针,我可以保证e->getName()100%工作.我的困惑是为什么在这种情况下它不起作用?我该怎么做才能使它正常工作?
#include <algorithm>
#include <vector>
#include <map>
#include <iostream>
#include "Task.h"
#include "Global.h" //Where my user defined global functions go
class Profile{
std::vector<std::unique_ptr<Task>>ToRun_;
std::vector<std::unique_ptr<Task>>Completed_;
std::vector<std::string>menu_;
//Ownership of ofstream object
std::ofstream& of_;
public:
Profile (const char* filename, std::ofstream& os, ARAIG_sensors& as);
virtual ~Profile();
void run();
//Executes specified number of tasks user specifies
void execute (unsigned long tasks);
void load_menu();
long show_menu()const;
long getInput(std::string prompt, int min, long max, menuOption option = NONE);
//Display all tasks to the screen
std::ostream& display_todo_tasks (std::ostream& os) const;
//Display completed tasks to the screen
std::ostream& display_completed_tasks (std::ostream& os)const;
//Display next task to the screen
std::ostream& display_next_task (std::ostream& os) const;
//Display last completed task
std::ostream& display_last_task(std::ostream& os)const;
};
Run Code Online (Sandbox Code Playgroud)
std::ostream& Profile::display_todo_tasks(std::ostream& os)const{
//Display all tasks in ToRun container
if(ToRun_.size() > 0){
new_line(user_interface_skip_screen);
std::cout << "\nTasks to be completed\n";
print_dash(29);
for_each(ToRun_.begin(), ToRun_.end(), [&os](std::unique_ptr<Task>& e){
if (e){
os << e->getName() <<'\n';
}
});
new_line(user_interface_system_message_skip_line - 1);
}else{
std::cerr << "There are no tasks to be performed in the task list.";
std::cerr.flush();
new_line(user_interface_system_message_skip_line);
}
return os;
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)std::ostream& Profile::display_todo_tasks(std::ostream& os)const
你的功能是一个const功能.因此,ToRun_是一个const对象.因此,从得到的迭代begin和end为const_iterator秒.因此,当你取消引用它们时你得到的是const参考.
你的lambda采用非const引用.因此不兼容.让它const参考,它应该没问题.