當我嘗試運行此玩具示例時,出現不一致的參數包編譯器錯誤。有人可以解釋爲什麼'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
您正在使用完美轉發。其中的重點是保存參數的值類別 - 推導左值參數的左值參考類型和右值參數的右值參考類型。看起來它正在完成工作,完美無缺。 –