当我尝试运行此玩具示例时,出现不一致的参数包编译器错误。有人可以解释为什么'int a'在这里被推断为int &?在下面的例子中,当我用int文字运行下面的'test'函数时,它工作正常。在此先感谢您的解释!不一致的参数包扣除int和int&in可变模板成员函数创建一个运行成员函数的线程
class Test {
public:
Test() {}
~Test() {
t.join();
}
void print(int num)
{
std::cout << num << std::endl;
}
template<class ...Args>
void test(void(Test::*b)(Args...) , Args&&... args)
{
t = std::thread(b, this, std::forward<Args>(args)...);
}
std::thread t;
};
int main()
{
int a = 123;
Test test;
test.test(&Test::print, a);
// test.test(&Test::print, 123); works
}
错误:
prog.cc: In function 'int main()':
prog.cc:82:40: error: no matching function for call to 'Test::test(
void (Test::*)(int), int&)'
test.test(&Test::print, a);
^
prog.cc:82:40: note: candidate is:
prog.cc:62:10: note: template<class ... Args> void Test::test(void
(Test::*)(Args ...), Args&& ...)
void test(void(Test::*b)(Args...) , Args&&... args)
^
prog.cc:62:10: note: template argument deduction/substitution failed:
prog.cc:82:40: note: inconsistent parameter pack deduction with 'int' and
'int&'
test.test(&Test::print, a);
^
什么是'printThree'? – Sergey
@谢谢错字 - 修正。抱歉。 – Mozbi
您正在使用完美转发。其中的重点是保存参数的值类别 - 推导左值参数的左值参考类型和右值参数的右值参考类型。看起来它正在完成工作,完美无缺。 –