I was just experimenting with C++ templates when my friend asked me about NumPy's vectorize function, so I tried to implement my own version of it in C++. However, I decided to make it instantly calling original function with vector, and not returning vectorized function, so I came up with this code:
#include <iostream>
#include <vector>
#include <functional>
#include <type_traits>
using namespace std;
int f(int x) {
return x + 5;
}
template<typename Func,
typename Arg,
typename Return = typename std::invoke_result_t<Func(Arg)>>
auto vectorizedCall(Func &func, std::vector<Arg> args) -> std::vector<Return> {
std::vector<Return> resultVector;
for(Arg a : args) {
resultVector.push_back(func(a));
}
return resultVector;
}
int main(int argc, char *argv[]) {
std::cout << f(5) << std::endl;
std::vector<int> args{5, 6, 1, 4};
auto vf = vectorizedCall(f, args);
for (int32_t n : vf) {
std::cout << n << std::endl;
}
return 0;
}
But code doesn't compile. Apparently, CLion shortens very-very long error log all the way to this:
candidate template ignored: substitution failure [with Func = int (int), Arg = int]: function cannot return function type 'int (int)'
However, I don't even try to return function type. What is the problem here and how can I solve it?
Change
typename Return = typename std::invoke_result_t<Func(Arg)>>
to
typename Return = typename std::invoke_result_t<Func,Arg>>
And you should be good to go!
You can see it working online at: https://rextester.com/QMI86655