在模板函数参数中使用std :: bind

时间:2018-08-21 13:29:49

标签: c++ c++11 templates

以前可能已经有人问过这个问题,但是我找不到正确的搜索关键字。

在编写测试功能时,我决定将测试代码重构为模板功能:

#include <iostream>
#include <functional>
#include <utility>
#include <vector>

template <typename In, typename Exp >
void runTest (
    std::pair<In, Exp> testParams, 
    Exp (*testFunction)(In)
    /*std::function< Exp(In)> testFunction */ )
{
    Exp result = testFunction(testParams.first);
    std::cout   << "Result : " << (result == testParams.second? "SUCCESS":"FAILURE")
                << " expected : " << testParams.second 
                << " got : "  << result
                << std::endl;
}

使用输入和预期结果填充向量,并将对与我们要测试的函数一起传递。对于一种功能非常有用:

long f1 (long a1)
{
    return a1 + 100;
}

void testf1()
{
    std::vector<std::pair<long, long> > testCases = {
        {100,200},
        {300,400}
    };
    for (auto test : testCases) {
        runTest (test, f1);
    }
}

,但随后必须测试具有两个参数的一个。 “好吧,没问题,我将std :: bind1st ...哦,那已不赞成使用...不过std :: bind应该应该使用它,对吗?第一个参数并将其传递给runTest”。

long f2 (long a1, long a2) 
{
    return a1+a2;
}

void testf2() 
{
    long a1 = 1234;
    std::vector<std::pair<long, long> > testCases = {
        {0,1234},
        {2,1238},
        {11,1245}
    };
    for (auto test : testCases){
        auto f2bound = std::bind(f2, a1, std::placeholders::_2);
        runTest (test, f2bound);
    }
}

但是the compiler says 'no'

~/src/cpplay/onestens$ g++ -m64 --std=c++11 -o soq.out soQuestionBind.cpp -g
soQuestionBind.cpp: In function ‘void testf2()’:
soQuestionBind.cpp:50:31: error: no matching function for call to ‘runTest(std::pair<long int, long int>&, std::_Bind<long int (*(long int, std::_Placeholder<2>))(long int, long int)>&)’
         runTest (test, f2bound);
                               ^
soQuestionBind.cpp:7:6: note: candidate: template<class In, class Exp> void runTest(std::pair<_T1, _T2>, Exp (*)(In))
 void runTest (
      ^
soQuestionBind.cpp:7:6: note:   template argument deduction/substitution failed:
soQuestionBind.cpp:50:31: note:   mismatched types ‘Exp (*)(In)’ and ‘std::_Bind<long int (*(long int, std::_Placeholder<2>))(long int, long int)>’
         runTest (test, f2bound);
                               ^

我落后于C ++ 11(以及14和17),但这应该可行,对吧?

我猜无法将std :: bind返回的对象强制转换为简单的函数指针...因此,必须如何定义我的模板参数以接受绑定函数?

1 个答案:

答案 0 :(得分:2)

  

我猜不能将std :: bind返回的对象强制转换为简单的函数指针。

正确。

获取通用可调用对象的典型方法是使用简单的模板参数。无需使用函数指针std::function或其他任何东西:

template <typename T, typename U, typename F>
void runTest (
    std::pair<T, U> testParams, 
    F testFunction )
{
    auto result = testFunction(testParams.first);
    // do something ...
}

现在您可以使用std::bind,但我建议改用lambda。