问题描述
给定一个应该将值移动到其他地方的函子,捕获“移动”值的正确方法是什么?
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 (将#修改为@)