通过const&或&&传递模板args

Sta*_*ked 12 c++ c++11

我有这个示例程序:

#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)

我也把它发布在Coliru上.

如您所见,我使用不同的方式传递参数:

  • 消息作为通用引用传递,因为它最终需要转发到PrintImpl函数.
  • 装饰在这里作为const ref传递,因为它的值被使用了两次,我不确定使用前进两次是否安全.(可能会被第一个前锋搬走?)
  • PrintImpl作为const引用传递,因为我没有看到任何使用forward的理由.但是,我不确定这是否明智.(我应该经过&&吗?如果是,我还应该使用std::forward吗?)

我做出了正确的选择吗?

Xeo*_*Xeo 4

我做出的选择正确吗?

是的(大部分)。

装饰在这里被捕获为 const ref,因为它的值被使用了两次,并且我不确定使用前向两次是否安全。(可能会被第一前锋移开?

std::forward当您多次执行此操作时,请勿使用,正是出于您列出的原因。

PrintImpl 被捕获为 const 引用,因为我没有看到任何使用转发的理由。

您可能想要做的是采用PrintImpl&&但不使用std::forward(将它们保留为左值),允许传递没有const- 限定的函数对象。operator()