在C++20中,假设我想std::make_unique
一个副本(或根据需要移动),并存储一个在转发引用中传递的类似函数的对象。。。
template<typename F>
std::unique_ptr<???> make_copy_of_functor(F&& f) {
return std::make_unique<???>(std::forward<F>(f));
}
???
中发生了什么?把F
放在那里正确吗。。。
template<typename F>
std::unique_ptr<F> make_copy_of_functor(F&& f) {
return std::make_unique<F>(std::forward<F>(f));
}
还是我需要用某种方式把它腐烂?(我可能对转发引用的引用折叠规则感到困惑。)
作为转发引用,当传递左值时,F
将被推导为左值引用,您可以使用std::decay
来移除引用部分(并为函数类型添加指针)。
template<typename F>
auto make_copy_of_functor(F&& f) {
return std::make_unique<std::decay_t<F>>(std::forward<F>(f));
}
您可以传递值,然后移动到一个新对象:
template <typename F>
auto make_copy_of_functor(F f) {
return std::make_unique<F>(std::move(f));
}