如何使用模板推导类型获得右值和左值引用的不同重载? [英] How to get different overloads for rvalue and lvalue references with a template-deduced type?
问题描述
我有一个函数 foo
通过引用获取参数,我希望它对右值和左值引用有不同的作用.(我还应该提到 foo()
尊重常量性;它不会改变引用的值.)我知道如果我写:
I have a function foo
taking a parameter by reference, and I want it to act differently on rvalue and on lvalue references. (I should also mention foo()
respects constness; it doesn't change the refered-to value.) I know that if I write:
template <typename T> foo(T&& x);
我已声明转发参考,而不是右值引用,意思是这样:
I've declared a forwarding reference, rather than an rvalue reference, meaning that this way:
template <typename T> foo(const T& x);
template <typename T> foo(T&& x);
可能得不到我想要的.
所以,我的问题是:影响两种引用之间不同行为的正确方法是什么?
So, my question is: What's the right way to affect different behavior between the two kinds of references?
推荐答案
标签调度是最简单的解决方案.
Tag dispatching is the simplest solution.
namespace details {
template <typename T>
void foo(std::true_type is_lvalue, const T& x) {
std::cout << x << " is an lvalue\n";
}
template <typename T>
void foo(std::false_type is_lvalue, T&& x) {
std::cout << x << " is an rvalue\n";
}
}
template <typename T>
void foo(T&& t) {
return details::foo(
typename std::is_lvalue_reference<T>::type{},
std::forward<T>(t)
);
}
当您实际上不想支持为重载解析目的选择两个版本时,SFINAE 是严重的矫枉过正.
SFINAE is serious overkill when you don't actually want to support neither version being selected for overload resolution purposes.
这篇关于如何使用模板推导类型获得右值和左值引用的不同重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!