How do I write a template function that accepts && and const & both?

for example

template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}

      

When i call

int i;
f(i); // call f(T&&) which I expect to call f(T const&), how to solve it?
f(10); // call f(T&&), that is fine

      

+3


source to share


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


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));
}

      



Live example

+4


source







All Articles