简体   繁体   中英

C++ accepting function as template and returning vector of function's return type

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM