我有以下C++14 lambda
#include <boost/optional.hpp>
int main(){
auto foo = [](auto && t)
{
using T = decltype(t);
return boost::optional<T>(std::forward<T>(t));
};
// This is fine because i is lvalue
auto i = 10;
foo(i);
// This fails because i is rvalue
foo(10);
}首先请注意,boost::optional可以包含左值引用,但不能包含右值引用。
是否可以使用上面的泛型lambda将rvalue作为副本处理。我想要的是像这样聪明的东西
using T = std::decay_if_rvalue<decltype(t)>::type有没有什么开箱即用的东西可以做到这一点?
发布于 2021-02-09 14:55:31
您可以将std::is_rvalue_reference与std::conditional一起使用,两者都来自<type_traits>标头。
auto foo = [](auto && t)
{
using Orig = decltype(t);
using T = std::conditional_t<std::is_rvalue_reference<Orig>::value,
std::decay_t<Orig>, Orig>;
return boost::optional<T>(std::forward<T>(t));
};发布于 2021-02-09 14:55:29
您可以将类型特征编写为
template< class T > struct remove_rvalue_reference {typedef T type;};
template< class T > struct remove_rvalue_reference <T&&> {typedef T type;};然后
using T = typename remove_rvalue_reference<decltype(t)>::type;然后
auto i = 10;
foo(i); // T will be int& in the lambda
foo(10); // T will be int in the lambda发布于 2021-02-09 15:10:37
在lubgr's answer上展开,您可以将条件类型封装在与C++14兼容的别名中,如下所示:
#include <type_traits>
template <class T>
using decay_rvalue_reference_t = std::conditional_t<
std::is_rvalue_reference<T>::value,
std::decay_t<T>::type,
T>;
auto foo = [](auto && t)
{
using T = decay_rvalue_reference_t<decltype(t)>;
return boost::optional<T>(std::forward<T>(t));
};https://stackoverflow.com/questions/66114232
复制相似问题