c++ - 根据函数签名将引用作为左值/右值传递

标签 c++ c++11 move

假设我有一些数据:

struct Bar {};

我需要包装一个函数并将这些数据提供给它。

template<typename F>
void foo(F f) {
    Bar bar;
    f(bar);
}

正如您在这个简单示例中所见:

  • bar 不是临时的
  • 调用f后我不需要它

我要支持多个函数签名,比如:

foo([](Bar){}); // (1)
foo([](Bar&){}); // (2)
foo([](Bar&&){}); // (3)

但是 gcc 提示:

f(bar); // (3) : cannot bind 'Bar' lvalue to 'Bar&&'
f(std::move(bar)); // (2) : no match for call to ...

你会怎么做才能同时获得两者?

最佳答案

struct BarIsh{
  Bar&b;
  operator Bar&&()&&{return std::move(b);}
  operator Bar&()&&{return b;}
};

然后 f(BarIsh{bar})

缺点是,如果 f 采用推导参数,它得到的是 BarIsh 而不是 Bar

假设您有一个 SFINAE 友好的 result_of...

template<class...>struct voider{using type=void;};
template<class...Ts>using void_t=typename voider<Ts...>::type;

template<class...>struct types{using type=types;};

namespace details{
  template<template<class...>class Z,class types,class=void>
  struct can_apply:std::false_type{};
  template<template<class...>class Z,class...Ts>
  struct can_apply<Z,types<Ts...>,void_t<Z<Ts...>>>:
    std::true_type
  {};
};
template<template<class...>class Z,class...Ts>
using can_apply=details::can_apply<Z,types<Ts...>>;

template<class Sig>
using result_of_t=typename std::result_of<Sig>::type;

template<class Sig>
using can_invoke=can_apply<result_of_t,Sig>;

现在我们可以测试了。

template<typename F>
void foo(F&& f,std::true_type)
{
  Bar bar;
  std::forward<F>(f)(std::move(bar));
}

template<typename F>
void foo(F&& f,std::false_type)
{
  Bar bar;
  std::forward<F>(f)(bar);
}


template<typename F>
void foo(F f)
{
  foo(std::forward<F>(f),can_apply<F(Bar&&)>{});
}

完成了。 (上面可能有错别字,手机写的代码)

关于c++ - 根据函数签名将引用作为左值/右值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389030/

相关文章:

c++ - 按值而不是键对映射进行排序

c++ - 如何返回当前具有焦点的QWidget

c++ - Valgrind 输出和 rdtsc 不一致......为什么会这样?

c++ - 在 C++20 中,如何编写连续迭代器?

linux - 匹配模式的 mv 文件夹

c++ - 在没有 move 构造函数的情况下 move 对象

c++ - 如果我要用它构造一个对象,我应该 move 被调用者的返回值吗?

c++ - 编译时是否需要短路评估规则?

c++ - mingw 5 std::this_thread 未定义

c++ - 用户定义的限定符