[英]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;
});
}
如您所見,我使用不同的方式來傳遞參數:
&&
嗎?如果是,我還應該使用std::forward
嗎?)我是否做出了正確的選擇?
我是否做出了正確的選擇?
是的(大部分)。
裝飾在這里被捕獲為 const ref,因為它的值被使用了兩次,我不確定使用 forward 兩次是否安全。 (可能會被第一個前鋒移開? )
當您多次使用std::forward
時,不要使用它,這正是您提出的原因。
PrintImpl 被捕獲為 const 引用,因為我沒有看到任何使用 forward 的理由。
您可能想要做的是采用PrintImpl&&
並且不使用std::forward
(將它們保留為左值),從而允許傳遞沒有const
限定operator()
函數對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.