template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}
當我打電話
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
template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}
當我打電話
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
這會是一個方法:
#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) {}
另一種可能性是標籤調度:
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>{});
}
的另一種方法是:
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));
}
是您要重載函數R值和L值和類型來區分,也模板? – Niall 2014-10-03 13:21:31
你想要rvalues去'T &&'重載和左值去'T const&'重載嗎? – 2014-10-03 13:25:10
可能相關:http://stackoverflow.com/q/25938749/3549027 – dlf 2014-10-03 13:25:23