我有这个示例程序:
#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;
});
}
正如您所见,我使用了不同的方法来传递参数:
- 消息作为通用引用被传递,因为最终需要将其转发到PrintImpl函数中。
- 装饰被作为常量引用传递,因为它的值被使用了两次,而且我不确定使用两个forward是否安全。(第一个forward可能会将其移动掉?)
- PrintImpl作为常量引用传递,因为我没有看到使用forward的任何理由。然而,我不确定这是否明智。(我应该使用
&&
传递吗?如果是,我也应该使用std::forward
吗?)
我的选择是正确的吗?
forward
与print_impl
一起使用,而不是decoration
,对吗? - sehe