无法在函数模板中使用 lambda 函数

Can't use the lambda function inside function template

本文关键字:lambda 函数 函数模板      更新时间:2023-10-16

我的函数模板有问题。

我有 3 个不同的集合,我有集合的迭代器。现在我必须创建一个函数模板"apply">,它将执行以下操作: 1. 遍历集合的所有元素并检查谓词是否为真:

1.1 如果谓词返回 true - 则需要使用 lambda"passed">更改集合元素

1.2 如果谓词返回 false = 则集合元素需要更改为 lambda"拒绝">

请给我一个例子,我应该怎么写。

非常感谢您的帮助。此处更新了代码:

#include <iostream>
#include <vector>
#include <list>
#include <functional>
using namespace std;
template<typename T>
void apply(T collBegin, T collEnd, function<bool(int)> f1, function<int(int)> f2, function<int(int)> f3)
{
for (T actualPosition = collBegin; actualPosition != collEnd; ++actualPosition) {
if (f1(*actualPosition)) {
//the argument matches the predicate function f1
*actualPosition = f2(*actualPosition);
}
else {
//the argument doesn't match the predicate function f1
*actualPosition = f3(*actualPosition);
}
}
}
int main()
{
int arr[]{ 1,2,3,4,5,6,7,8,9 };
auto predicate = [](int arg) -> bool { return arg % 2 == 0; };
auto passed = [](int arg) -> int { return arg / 2; };
auto rejected = [](int arg) -> int { return (3 * arg) + 1; };
apply(arr, arr + std::size(arr), predicate, passed, rejected);
std::vector<int> vec(arr, arr + std::size(arr));
apply(vec.begin(), vec.end(), predicate, passed, rejected);
std::list<int> lis(vec.begin(), vec.end());
apply(lis.begin(), lis.end(), predicate, passed, rejected);

for (auto e : lis) std::cout << e << " ";
std::cout << 'n';
}

此代码有效。但我想把它从 int 更改为 T。我该怎么做?

那么代码应该是什么样子的?你能写一个例子吗?

以下内容编译并运行,但我不确定这是否是您想要的:

#include <iostream>
#include <vector>
#include <list>
#include <functional>
#include <algorithm>
template<typename T, typename U>
void apply(T collBegin, T collEnd, std::function<bool(U const &)> f1, std::function<U(U const &)> f2, std::function<U(U const &)> f3)
{
std::for_each(collBegin, collEnd, [&](auto &el) { el = f1(el) ? f2(el) : f3(el); });
}
int main()
{
std::function<bool(int const &)> predicate = [](int const &arg) -> bool { return arg % 2 == 0; };
std::function<int(int const &)> passed = [](int const &arg) -> int { return arg / 2; };
std::function<int(int const &)> rejected = [](int const &arg) -> int { return (3 * arg) + 1; };
int arr[]{ 1,2,3,4,5,6,7,8,9 };
apply(arr, arr + sizeof(arr)/sizeof(int), predicate, passed, rejected);
std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
apply(vec.begin(), vec.end(), predicate, passed, rejected);
std::list<int> lis(vec.begin(), vec.end());
apply(lis.begin(), lis.end(), predicate, passed, rejected);
for (auto e : lis) std::cout << e << " ";
std::cout << 'n';
}

https://ideone.com/A30Dl9

1 2 16 4 4 5 34 1 7