mardi 1 août 2017

Inconsistent parameter pack deduction int and int& in variadic templated member function that creates a thread that runs a member function

I'm getting an inconsistent parameter pack compiler error when I try to run this toy example. Could someone shed light on why 'int a' is being deduced as an int& here? In the example below, when I run the 'test' function below with an int literal it works fine. Thanks in advance for the explanation!

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::printThree, a);
    // test.test(&Test::printTree, 123); works
}

Error:

prog.cc: In function 'int main()':
prog.cc:82:40: error: no matching function for call to 'Test::test(char, 
void (Test::*)(int), int&)'
     test.test('a', &Test::printThree, a);
                                    ^
prog.cc:82:40: note: candidate is:
prog.cc:62:10: note: template<class ... Args> void Test::test(char, void 
(Test::*)(Args ...), Args&& ...)
     void test(char a, 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('a', &Test::printThree, a);
                                    ^

Aucun commentaire:

Enregistrer un commentaire