简体   繁体   English

通过 const& 或 && 传递模板参数

[英]Pass template args by const& or &&

I have this example program:我有这个示例程序:

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

I also posted it on Coliru.我也把它贴在 Coliru 上。

As you can see I use different ways to pass the arguments:如您所见,我使用不同的方式来传递参数:

  • Message is passed as a universal reference because it eventually needs to be forwarded to the PrintImpl function.消息作为通用引用传递,因为它最终需要转发到 PrintImpl 函数。
  • Decoration is passed as const ref here because its value is used twice and I'm not sure if using forward twice would be safe.装饰在这里作为 const ref 传递,因为它的值被使用了两次,我不确定使用前向两次是否安全。 (It might be moved away by the first forward?) (它可能会被第一个前锋移开?)
  • PrintImpl is passed as const reference because I don't see any reason to use forward. PrintImpl 作为 const 引用传递,因为我没有看到任何使用 forward 的理由。 However, I'm not certain if this is wise.但是,我不确定这是否明智。 (Should I pass by && ? If yes, should I also use std::forward ?) (我应该通过&&吗?如果是,我还应该使用std::forward吗?)

Am I making the right choices?我是否做出了正确的选择?

Am I making the right choices?我是否做出了正确的选择?

Yes (mostly).是的(大部分)。

Decoration is captured as const ref here because its value is used twice and I'm not sure if using forward twice would be safe.装饰在这里被捕获为 const ref,因为它的值被使用了两次,我不确定使用 forward 两次是否安全。 ( It might be moved away by the first forward? ) 可能会被第一个前锋移开?

Don't use std::forward when you'd do it multiple times, exactly for the reason you layed out.当您多次使用std::forward时,不要使用它,这正是您提出的原因。

PrintImpl is captured as const reference because I don't see any reason to use forward. PrintImpl 被捕获为 const 引用,因为我没有看到任何使用 forward 的理由。

What you might want to do is take PrintImpl&& and don't use std::forward (keeping them as lvalues), allowing function objects without const -qualified operator() to be passed.您可能想要做的是采用PrintImpl&&并且不使用std::forward (将它们保留为左值),从而允许传递没有const限定operator()函数对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM