Stream template member function std in class template: compiler error

Here is the code. It does not compile in vs2013 but does compile in gcc4.8

error C2665: 'std :: thread :: thread': none of the 4 overloads could convert all argument types

Since I am using vs2013, can anyone provide a workaround?

#include <iostream>
#include <thread>

template<typename T> 
class TestClass
{
public:
    TestClass(){};
    ~TestClass(){};

    T  t;

    template<typename U>
    void fun(U u)
    {
        std::cout << "fun: " << u << '\n';
    }
};

int main()
{
    TestClass<double>  A;

    auto aaa = std::thread(&TestClass<double>::fun<int>, &A, 1);
}

      

+2


source to share


2 answers


You can just use lambda and not monkey with member function pointers:



auto aaa = thread( [&]{ A.fun(1); } );
aaa.join();

      

+7


source


There is another way you can achieve the above problem if you don't mind! First, just look at the explicit constructor of the stream object:

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );

      

f - A generic reference for a functional object.

args - variational arguments for the function (functor) f.



(I will not explain deeper or deeper about the use of variation call used here). So now we know that we can deal with functors, Define a functor (function object) as shown below:

template<typename T>
class TestClass
{
public:
    TestClass(){};
    ~TestClass(){};

    T  t;

    template<typename U>
    void operator()(U u1,U u2){
        std::cout << "fun: " << u1*u2 << '\n';
    }

};
int main()
{
    TestClass<double>  A;
    auto aaa = std::thread(A,1,100);// calling functor A(1,100)
    aaa.join()
    //or if you can move object from main thread to manually created thread aaa ,it more elegant.
    auto aa = std::thread(std::move(A),1,100);
    aa.join();
    A(1, 99);
    system("Pause");
    return 0;
}

      

// Note that I did not use the guard system. If you are using a static function, you do not need to bind the appropriate instance every time that might change expected runtime behavior, so you need to manage,

 template<typename U>
    static void fun(U u)
    {
        std::cout << "fun: " << u << '\n';
    }
then invoke the function,
int main()
{
    TestClass<double>  A;
    auto aaa = std::thread(&TestClass<double>::fun<int>, 1);
    system("Pause");
    return 0;
}

      

+1


source







All Articles