![](/img/trans.png)
[英]How does the compiler find the template function X::max(T const&, T const&) through ADL in the code below?
[英]How to write a template function accepting && and const& both?
例如
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.