gpt4 book ai didi

c++ - 右值引用是否有reference_wrapper<>?

转载 作者:IT老高 更新时间:2023-10-28 22:59:33 24 4
gpt4 key购买 nike

我想知道如何完成以下操作

void f(string &&s) { 
std::string i(move(s));
/* other stuff */
}

int main() {
std::string s;
bind(f, s)(); // Error.
bind(f, move(s))(); // Error.
bind(f, ref(s))(); // Error.
}

如何传递右值引用并将其作为右值引用(可能已包装)存储在调用包装器中?我知道我可以手动编写一个类,如 std::reference_wrapper<>具有到 T&& 的转换函数,但我宁愿避免这种情况并使用标准技术。


我按照 AProgrammer 的建议实现了它:

template<typename T> struct adv { 
T t;
explicit adv(T &&t):t(forward<T>(t)) {}
template<typename ...U> T &&operator()(U &&...) {
return forward<T>(t);
}
};

template<typename T> adv<T> make_adv(T &&t) {
return adv<T>{forward<T>(t)};
}

namespace std {
template<typename T>
struct is_bind_expression< adv<T> > : std::true_type {};
}

现在我可以说

void f(string &&s) { 
std::string i(move(s));
/* other stuff */
}

int main() {
std::string s;
bind(f, make_adv(move(s)))(); // Works!
}

如果我们将左值传递给 make_adv , 它会将其作为引用输入参数的左值转发,因此它可以用作 std::ref 的替代品, 在这种情况下。

最佳答案

我对此的看法。

N3225 中的 20.8.10.1.2/10

The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows:

  • if TiD is reference_wrapper, the argument is tid.get() and its type Vi is T&;
  • if the value of is_bind_expression::value is true, the argument is tid(std::forward(uj)...) and its type Vi is result_of::type;
  • if the value j of is_placeholder::value is not zero, the argument is std::forward(uj) and its type Vi is Uj&&;
  • otherwise, the value is tid and its type Vi is TiD cv &.

因此,拥有右值引用的唯一可能性是拥有 is_bind_expression<TiD>::value真或is_placeholder<TiD>::value不为零。第二种可能性具有您不想要的含义,而第一种实现想要的结果意味着如果我们限制为标准提供的类型,我们试图解决的问题就会得到解决。因此,唯一的可能性是提供您自己的包装器和 is_bind_expression<TiD> 的特化。 (这是 20.8.10.1.1/1 允许的),因为我没有看到。

关于c++ - 右值引用是否有reference_wrapper<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5126219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com