我试图在向量上应用变换,同时还在变换函数中添加索引。我正在使用以下转换函数transformWithIndex
。如果我从idx
中删除了result.push_back(itransformationFunction(idx, element));
,它就可以正常工作。
我知道我还有一个争论。但我不明白 修改转换函数以处理IDX。
// Example program That can be tested
#include <iostream>
#include <string>
#include <vector>
template <typename Range, class TransformationFunction>
inline std::vector<typename std::result_of<TransformationFunction(typename Range::value_type)>::type>
transformWithIndex(const Range &iRange, const TransformationFunction &itransformationFunction) {
std::vector<typename std::result_of<TransformationFunction(typename Range::value_type)>::type> result;
int idx = 0;
for (auto &&element : iRange) {
result.push_back(itransformationFunction(idx, element));
idx++;
}
return result;
}
int main()
{
std::vector<int> source = {1, 2, 3};
std::vector<int> result = transformWithIndex(source, [](int i) { return ++i; });
return 0;
}
错误如下:
> In instantiation of 'std::vector<typename
> std::result_of<TransformationFunction(typename
> Range::value_type)>::type> transformWithIndex(const Range&, const
> TransformationFunction&) [with Range = std::vector<int>;
> TransformationFunction = main()::<lambda(int)>; typename
> std::result_of<TransformationFunction(typename
> Range::value_type)>::type = int]': 21:82: required from here 12:58:
> error: no match for call to '(const main()::<lambda(int)>) (int&,
> const int&)' 21:58: note: candidates are: 12:58: note: int (*)(int)
> <conversion> 12:58: note: candidate expects 2 arguments, 3 provided
> 21:65: note: main()::<lambda(int)> 21:65: note: candidate expects 1
> argument, 2 provided
答案 0 :(得分:2)
您致电itransformationFunction(idx, element)
(2个参数)
而您的lambda曾经期望一个。
将通话更改为:
transformWithIndex(source, [](int index, int &elem) { return index + 1; })
和您的result_of
也应固定为包括索引:
template <typename Range, class TransformationFunction>
std::vector<typename std::result_of<TransformationFunction(std::size_t, typename Range::value_type)>::type>
transformWithIndex(const Range &iRange, const TransformationFunction &itransformationFunction) {
std::vector<typename std::result_of<TransformationFunction(std::size_t, typename Range::value_type)>::type> result;
int idx = 0;
for (auto &&element : iRange) {
result.push_back(itransformationFunction(idx, element));
idx++;
}
return result;
}
和std::decay_t
应该应用于处理函子返回引用或const对象的情况。