簡體   English   中英

std線程調用模板成員函數模板類:編譯錯誤

[英]std thread call template member function of template class: compiler error

這是代碼。 它不在vs2013中編譯,但在gcc4.8中編譯

錯誤C2665:'std :: thread :: thread':4個重載中沒有一個可以轉換所有參數類型

由於我使用vs2013,任何人都可以提供解決方法嗎?

#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);
}

您可以簡單地使用lambda而不是使用成員函數指針進行修改:

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

還有另一種方法可以實現上述問題,如果您願意的話! 首先看一下線程對象的顯式構造函數:

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

f - 功能對象的通用引用。

args - 函數的變量參數(仿函數) f

(我不會更深入地解釋這里使用的可變參數調用)。 所以現在我們知道我們可以處理仿函數, 定義一個仿函數(函數對象),如下所示:

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's more elegant.
    auto aa = std::thread(std::move(A),1,100);
    aa.join();
    A(1, 99);
    system("Pause");
    return 0;
}

//請注意這里我沒有使用任何儲物櫃防護系統。 如果您使用靜態函數,則每次這可能會改變您的預期運行時行為時不必綁定相應的實例,因此您必須進行托管,

 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM