c++ - rvalue or lvalue (const) reference parameter -
i want pass parameter(s) (of concrete type, int
) member function r- or l- value (const) reference. solution is:
#include <type_traits> #include <utility> struct f { using desired_parameter_type = int; template< typename x, typename = typename std::enable_if< std::is_same< typename std::decay< x >::type, desired_parameter_type >::value >::type > void operator () (x && x) const { // or static_assert(std::is_same< typename std::decay< x >::type, desired_parameter_type >::value, ""); std::forward< x >(x); // useful } };
another exaple here http://pastebin.com/9kghmsvc.
but verbose. how in simpler way?
maybe should use superposition of std::remove_reference
, std::remove_const
instead of std::decay
, there simplification here.
if understand question correctly, wish have single function parameter either rvalue reference (in case rvalue provided) or lvalue reference const
(in case lvalue provided).
but function do? well, since must able handle both cases, including case lvalue provided, cannot modify input (at least not 1 bound x
parameter) - if did, violate semantics of const
reference.
but again, if cannot alter state of parameter, there no reason allowing rvalue reference: rather let x
lvalue-reference const
time. lvalue references const
can bind rvalues, allowed pass both rvalues , lvalues.
if semantics of function different based on passed, makes more sense write two such functions: 1 takes rvalue reference , 1 takes lvalue reference const
.
Comments
Post a Comment