recipes
recipes copied to clipboard
fix-universal-reference-and-perfect-forwarding-bug
在阅读代码时发现代码中的完美转发是有问题的:因为模板类的成员方法只是一个普通的函数,并不是一个模板函数,所以他们的参数不会触发类型推导,所以对于T&&类型只是一个普通的右值引用。原本的代码只能接收右值引用参数,但是这显然不是代码的本意,因为后面使用了std::forward进行完美转发,因此应该是一个universal reference才对。测试代码如下:
#include <SignalSlotTrivial.h>
void compare1(string x, string y) {
cout << "compare1" << endl;
}
int main() {
SignalTrivial<void(string, string)> signal;
function<void(string, string)> comapre3 = [](string x, string y) {
cout << "compare2" << endl;
};
signal.connect(compare1);
signal.connect([](string x, string y) {
cout << "compare2" << endl;
});
//error:Rvalue reference to type 'function<...>' cannot bind to lvalue of type 'function<...>'
signal.connect(comapre3);
signal.call("Hello", "hello");
string s1 = "Hello";
string s2 = "hello";
//error:Rvalue reference to type 'basic_string<...>' cannot bind to lvalue of type 'basic_string<...>'
signal.call(s1, s2);
return 0;
}
对于支持多线程实现同样也存在类似的问题。通过将connect
和call
函数都转换为模板成员函数就可以解决这个问题。