gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:29 24 4
gpt4 key购买 nike

这可能以前以某种方式被问过,但我找不到合适的搜索关键字。

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

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

用输入和预期结果填充一个 vector ,并将这些对与我们要测试的函数一起传递。非常适合一个功能:

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 返回的对象不能被强制转换成一个简单的函数指针...那么我的模板参数必须如何定义才能接受绑定(bind)函数?

最佳答案

I guess the object returned by std::bind couldn't be coerced into a simple function pointer.

正确。

获取通用可调用对象的典型方法是使用简单的模板参数。无需使用函数指针、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。

关于c++ - 在模板函数参数中使用 std::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51949873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com