How do I write a template function that accepts && and const & both?
2 answers
This will be one of the ways:
#include <type_traits>
template<typename T>
typename std::enable_if< !std::is_lvalue_reference<T>::value >::type
f(T&& t) {}
template<typename T> void f(T const& t) {}
Another possibility is to send tags:
template<typename T>
void f_(const T&, std::true_type) { std::cout << "const T&\n"; }
template<typename T>
void f_(T&&, std::false_type) { std::cout << "T&&\n"; }
template<typename T>
void f(T&& t)
{
f_(std::forward<T>(t), std::is_lvalue_reference<T>{} );
}
+7
source to share
Another variant:
template<typename T>
struct f_caller
{
void operator () (T&& ) { std::cout << "T&&" << std::endl; }
void operator () (T const& ) { std::cout << "const T&" << std::endl; }
};
template <typename T>
void f(T&& t)
{
f_caller<typename std::decay<T>::type>()(std::forward<T>(t));
}
+4
source to share