c++ - Variadic templates argument fowarding -
say have function foo()
takes advantage of c++ variadic templates feature. now, what's difference between these implementations:
template <typename... args> void foo(args... args) { whatever(args...); } template<typename... args> void foo(args&... args) { whatever(args...); } template<typename... args> void foo(args... args) { whatever(&args...); } template<typename... args> void foo(args&&... args) { whatever(std::forward<args>(args)...); }
template <typename... args> void foo(args... args) { whatever(args...); }
foo
gets copies of args
, passes them whatever
l-values.
template<typename... args> void foo(args&... args) { whatever(args...); }
foo
gets l-value references args
, passes them whatever
l-values.
template<typename... args> void foo(args... args) { whatever(&args...); }
foo
gets copies of args
, passes them whatever
pointers l-values. careful of object lifetimes here.
template<typename... args> void foo(args&&... args) { whatever(std::forward<args>(args)...); }
foo
gets forwarding references args
. whether l-values or r-values depends on happens @ call site. perfect-forwarded whatever
, preserving reference type. scott meyers called these "universal" references, forwarding reference preferred terminology now.
Comments
Post a Comment