更新时间:2023-11-12 09:42:04
知道为什么它没有实施。
Well, I'm not aware of why it wasn't implemented. Perhaps it wasn't proposed, or perhaps there were some subtle gotchas.
也就是说,我想你可以很容易地写。
That said, I think you can write it pretty easily
template<typename T>
struct protect_wrapper : T
{
protect_wrapper(const T& t) : T(t)
{
}
protect_wrapper(T&& t) : T(std::move(t))
{
}
};
template<typename T>
typename std::enable_if< !std::is_bind_expression< typename std::decay<T>::type >::value,
T&& >::type
protect(T&& t)
{
return std::forward<T>(t);
}
template<typename T>
typename std::enable_if< std::is_bind_expression< typename std::decay<T>::type >::value,
protect_wrapper<typename std::decay<T>::type > >::type
protect(T&& t)
{
return protect_wrapper<typename std::decay<T>::type >(std::forward<T>(t));
}
这两个版本的保护使得非绑定表达式不被包装他们只是通过)。一切都通过move / copy传递给 protect_wrapper
,它只是从类型继承。
The two versions of protect are so that non-bind expressions are not wrapped (they just pass through). Everything else is passed by move/copy to the protect_wrapper
, which simply inherits from the type. This allows the type's functions to pass through, or for it to convert to the type.
它可以复制/移动,所以它可以安全地使用rvals。这个函数允许类型的函数通过,或者转换为类型。因为它只保护bind_expressions的类型,所以最小化必须发生的复制量。
It makes a copy/move however, so it can be safely used with rvals. And since it only protects types that are bind_expressions, it minimizes the amount of copying that has to occur.
int main()
{
//// Ok, with protect
auto bind_expr =
std::bind<int>(invoke_with_42{}
, protect(std::bind(&add, 1, std::placeholders::_1)));
std:: cout << bind_expr() << std::endl;
return 0;
}