在我的程序中,我有模板类,这些模板类主要是用于特殊目的 std::function<..> 的包装器。最小的例子是:
template
class Foo {
công cộng:
explicit Foo(std::function _function)
: function_(_function)
{}
template
void Bar(Arguments&&... _args) {
function_(std::forward(_args)...);
}
riêng tư:
std::function function_;
};
这些模板的实例通常是左值引用、右值引用或无引用类型的组合。问题在于,当某些参数是非引用类型(例如 int 或 std::vector)时,调用 Bar 会导致错误。解决方法是声明一个临时变量,然后将其移动到函数调用中。
int chính(){
Foo test1([](int x) { });
const int x = 1;
test1.Bar(x); // [Error] cannot bind rvalue reference of type 'int&&' to lvalue of type 'const int'
int tmp = x;
test1.Bar(tmp); // [Error] cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'
test1.Bar(std::move(tmp)); // [OK] But I don't want to have to reassign and move every time I use this.
/* I want perfect forwarding on variables that can be forwarded. */
/* There are cases when the templates are like this with a combination of l-value ref and r-value ref and non-ref types. */
Foo&, std::vector&&, int> test2([](const std::vector&, std::vector&&, int) { });
test2.Bar(std::vector(1, 2), std::vector(1, 2), x); // [Error] cannot bind rvalue reference of type 'int&&' to lvalue of type 'const int'
trả về 1;
}
我希望能够将 Bar 与任何模板参数一起使用,而不必每次都重新分配和 std::move() ,而且还可以完美转发 ref 参数。有没有办法做到这一点?
biên tập在网上浏览了一下之后 - 问题是 std::function function_;
不是采用通用引用而是采用 r-val 引用的函数。因此尝试转发无引用类型会引发错误。
那么接下来的问题是,是否可以拥有并存储一个采用通用引用的 std::function?
hiện hữustd::function
,你实际上期望 r 值引用,你可能想要 std::function
:
template
class Foo {
công cộng:
explicit Foo(std::function _function)
: function_(_function)
{}
template
void Bar(Arguments&&... _args) {
function_(std::forward(_args)...);
}
riêng tư:
std::function function_;
};
Demo
如果合适,你可以去掉 std::chức năng
:
template
class Foo {
công cộng:
explicit Foo(F f) : f(f) {}
template
auto operator ()(Ts&&... args) const
-> decltype(f(std::forward(args)...))
{
return f(std::forward(args)...);
}
riêng tư:
F f;
};
template
Foo MakeFoo(F f) { return Foo{f}; }
Demo
Tôi là một lập trình viên xuất sắc, rất giỏi!