如何解决在函子中捕获要移动的值
给定一个应该将值移动到其他地方的函子,捕获“移动”值的正确方法是什么?
template<typename TYPE>
struct MovingFunctor {
MovingFunctor(TYPE & moveto,TYPE ?? moved) : destination(moveto),capture(???(value)){}
void operator()() {
destination= std::move(capture);
}
TYPE & destination;
TYPE ?? capture;
};
int main() {
std::unique_ptr<double> aValue;
auto anotherValue = std::make_unique<double>(1);
MovingFunctor<std::unique_ptr<double>>(aValue,std::move(anotherValue))();
}
基本上,我应该用什么代替“??”在什么情况下?
该示例是我所拥有的实际案例的简化版本,其中涉及 boost::variant
和 boost::apply_visitor
,所以我想我应该坚持使用函子风格。
函子被构建为右值并传递给boost::apply_visitor
。我还不确定,但它可能会因为 bad_get 而抛出,所以也许我需要做一些无法移动的事情。
try{
boost::apply_visitor(MovingFunctor<std::unique_ptr<double>>(destination,std::move(moved)),...);
}catch(boost::bad_get){
//... do something with failed-to-move "moved"
}
我使用 c++11,所以没有模板化的 lambdas。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。