【问题标题】:C++ accepting function as template and returning vector of function's return typeC++接受函数作为模板并返回函数返回类型的向量
【发布时间】:2021-03-23 23:43:19
【问题描述】:

当我的朋友向我询问 NumPy 的矢量化函数时,我只是在试验 C++ 模板,因此我尝试在 C++ 中实现我自己的版本。但是,我决定让它立即用向量调用原始函数,而不是返回向量化函数,所以我想出了这个代码:

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

但代码无法编译。显然,CLion 会一直缩短非常长的错误日志:

candidate template ignored: substitution failure [with Func = int (int), Arg = int]: function cannot return function type 'int (int)'

但是,我什至不尝试返回函数类型。这里有什么问题,我该如何解决?

【问题讨论】:

  • 为什么引用Func
  • invoke_result_t&lt;F, Args...&gt; 不是invoke_result_t&lt;F(Args...)&gt;
  • std::transform 做同样的事情,但使用的是迭代器。
  • std::vector&lt;decltype(func(args.front()))&gt; resultVector; 并删除 Return 参数和尾随返回类型。 Demo。就是说 - 是的,正如@alain 所说,您正在重新发明std::transform

标签: c++ templates template-meta-programming c++20


【解决方案1】:

改变

typename Return = typename std::invoke_result_t<Func(Arg)>>

typename Return = typename std::invoke_result_t<Func,Arg>>

你应该很高兴!

您可以在线查看它的工作原理:https://rextester.com/QMI86655

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2022-07-22
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    相关资源
    最近更新 更多