簡體   English   中英

通過 const& 或 && 傳遞模板參數

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

我有這個示例程序:

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

我也把它貼在 Coliru 上。

如您所見,我使用不同的方式來傳遞參數:

  • 消息作為通用引用傳遞,因為它最終需要轉發到 PrintImpl 函數。
  • 裝飾在這里作為 const ref 傳遞,因為它的值被使用了兩次,我不確定使用前向兩次是否安全。 (它可能會被第一個前鋒移開?)
  • PrintImpl 作為 const 引用傳遞,因為我沒有看到任何使用 forward 的理由。 但是,我不確定這是否明智。 (我應該通過&&嗎?如果是,我還應該使用std::forward嗎?)

我是否做出了正確的選擇?

我是否做出了正確的選擇?

是的(大部分)。

裝飾在這里被捕獲為 const ref,因為它的值被使用了兩次,我不確定使用 forward 兩次是否安全。 可能會被第一個前鋒移開?

當您多次使用std::forward時,不要使用它,這正是您提出的原因。

PrintImpl 被捕獲為 const 引用,因為我沒有看到任何使用 forward 的理由。

您可能想要做的是采用PrintImpl&&並且不使用std::forward (將它們保留為左值),從而允許傳遞沒有const限定operator()函數對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM