c++ - Pass template args by const& or && -


i have 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 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 posted on coliru.

as can see use different ways pass arguments:

  • message passed universal reference because needs forwarded printimpl function.
  • decoration passed const ref here because value used twice , i'm not sure if using forward twice safe. (it might moved away first forward?)
  • printimpl passed const reference because don't see reason use forward. however, i'm not if wise. (should pass &&? if yes, should use std::forward?)

am making right choices?

am making right choices?

yes (mostly).

decoration captured const ref here because value used twice , i'm not sure if using forward twice safe. (it might moved away first forward?)

don't use std::forward when you'd multiple times, reason layed out.

printimpl captured const reference because don't see reason use forward.

what might want take printimpl&& , don't use std::forward (keeping them lvalues), allowing function objects without const-qualified operator() passed.


Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -