我有这个示例程序:
#include <iostream>
template<typename Message, typename Decoration, typename PrintImpl>
void print_surrounded(Message&& msg, const Decoration& decoration, const PrintImpl& print_impl)
{
print_impl(decoration); // should forward be used?
print_impl(" ");
print_impl(std::forward<Message>(msg));
print_impl(" ");
print_impl(decoration);
}
template<typename Message, typename PrintImpl>
void pretty_print(Message&& msg, const PrintImpl& print_impl)
{
print_surrounded(std::forward<Message>(msg), "***", print_impl);
}
int main()
{
pretty_print("So pretty!", [](const char* msg) {
std::cout << msg;
});
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用不同的方式传递参数:
&&
吗?如果是,我还应该使用std::forward
吗?)我做出了正确的选择吗?
我做出的选择正确吗?
是的(大部分)。
装饰在这里被捕获为 const ref,因为它的值被使用了两次,并且我不确定使用前向两次是否安全。(可能会被第一前锋移开?)
std::forward
当您多次执行此操作时,请勿使用,正是出于您列出的原因。
PrintImpl 被捕获为 const 引用,因为我没有看到任何使用转发的理由。
您可能想要做的是采用PrintImpl&&
但不使用std::forward
(将它们保留为左值),允许传递没有const
- 限定的函数对象。operator()