【问题标题】:How to use template function parameter in std::bind?如何在 std::bind 中使用模板函数参数?
【发布时间】:2014-11-17 20:43:06
【问题描述】:

我正在尝试创建一个并行化 for 的函数。 我正在使用 SFML 的线程和带有模板的 std::bind。

这是我尝试过的。

#include <SFML/System.hpp>

#include <iostream>
#include <functional>
sf::Mutex mutex;

template <typename F>
void For_Multitread(F Function, std::vector<int>& A);

template <typename F>
void Execute_For(F Function, std::vector<int>& A, int Depart, int Fin);
void Compute(int& Number);

template <typename F>
void For_Multitread(F Function, std::vector<int>& A)
{
    for (int Thread = 0; Thread < 2; Thread++)
    {
        sf::Thread thread(std::bind(&Execute_For, Function, A, Thread * 5, (Thread+1)*5));
        thread.launch();
    }

    mutex.lock();

    for (int i = 0; i < 10; ++i)
        std::cout << A[i] << std::endl;

    mutex.unlock();
}

template <typename F>
void Execute_For(F Function, std::vector<int>& A, int Depart, int Fin)
{
    for (int i = Depart; i < Fin; ++i)
    {
        Function(A[i]);
    }
}

void Compute(int& Number)
{
    Number++;
}

int main()
{
    std::vector<int> A;
    for (int i =0; i < 10; i++)
        A.push_back(i);

    For_Multitread(&Compute, A);

    return 0;
}

错误是

no matching function for call to 'bind(&lt;unresolved overloaded function type&gt;, void (*&amp;)(int&amp;), std::vector&lt;int&gt;&amp;, int, int)

我是否错过了一些非常重要的事情?

【问题讨论】:

    标签: c++ multithreading templates c++11 stdbind


    【解决方案1】:

    Execute_For 是一个函数模板,因此您需要为它提供类型模板参数:

    std::bind(&Execute_For<F>, Function, A, Thread * 5, (Thread+1)*5)
    //        ~~~~~~~~~~~~~~^            
    

    或使用static_cast:

    std::bind(static_cast<void(*)(F,std::vector<int>&,int,int)>(&Execute_For), Function, A, Thread * 5, (Thread+1)*5)
    //        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
    

    【讨论】:

    • 谢谢你解决了这个问题,我理解这个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2019-04-30
    • 2013-01-21
    • 2016-04-26
    • 1970-01-01
    • 2014-01-09
    • 2021-12-31
    相关资源
    最近更新 更多