假设我有一些要推导的参数类型(或几种参数类型)的函数。我也希望基于事实是右值或左值的不同行为。由于完美的转发,直接写作会导致明显的陷阱(对于有经验的人):
#include <iostream>
#include <vector>
template <typename T>
void f (T &&v) // thought to be rvalue version
{
// some behavior based on the fact that v is rvalue
auto p = std::move (v);
(void) p;
}
template <typename T>
void f (const T &v) // never called
{
auto p = v;
(void) p;
}
int main ()
{
std::vector<int> x = {252, 135};
auto &z = x;
f (z);
std::cout << x.size () << '\n'; // woah, unexpected 0 or crash
}
尽管这种行为的偷偷摸摸的性质已经是一个有趣的问题,但是我的问题实际上是不同的-对于这种情况,有什么好的,简洁的,可理解的解决方法?
[如果没有推断出完美转发的类型(例如,它是外部类的已知模板参数或类似的东西),则众所周知的解决方法是使用typename identity<T>::type&&
而不是T&&
,但是由于相同的构造是避免类型推断的一种解决方法在这种情况下没有帮助。我可能可以想象有一些解决方法,但是代码的清晰度可能会被破坏,并且看起来与类似的非模板功能完全不同。
SFINAE隐藏在模板参数列表中:
#include <type_traits>
template <typename T
, typename = typename std::enable_if<!std::is_lvalue_reference<T>{}>::type>
void f(T&& v);
template <typename T>
void f(const T& v);
隐藏在返回类型中的SFINAE:
template <typename T>
auto f(T&& v)
-> typename std::enable_if<!std::is_lvalue_reference<T>{}>::type;
template <typename T>
void f(const T& v);
在c++14中typename std::enable_if<!std::is_lvalue_reference<T>{}>::type
可以缩写为:
std::enable_if_t<!std::is_lvalue_reference<T>{}>
无论如何,即使您觉得更简洁,也可以使用别名模板来缩短语法:
c++11
template <typename T>
using check_rvalue = typename std::enable_if<!std::is_lvalue_reference<T>{}>::type;
具有DEMO 3概念:
c++20
template <typename T>
concept rvalue = !std::is_lvalue_reference_v<T>;
void f(rvalue auto&& v);
void f(const auto& v);
第二级实施情况如何:
DEMO 4
我认为SFINAE应该有所帮助:
#include <utility>
#include <type_traits>
// For when f is called with an rvalue.
template <typename T>
void f_impl(T && t, std::false_type) { /* ... */ }
// For when f is called with an lvalue.
template <typename T>
void f_impl(T & t, std::true_type) { /* ... */ }
template <typename T>
void f(T && t)
{
f_impl(std::forward<T>(t), std::is_reference<T>());
}