c++ - C++ 中的 Reader 仿函数

标签 c++ templates haskell functor category-theory

我正在尝试用 C++ 实现一个读取器仿函数。 相应的 Haskell 定义是 fmap::(a -> b) -> (r -> a) -> (r -> b)

我的 C++ 版本是:

template<class A, class B, class R>
B fmap(const std::function<B(A)> &funcA, const std::function<A(R)> &funcR) {
    return funcA(funcR());
}

std::string function_1(int n);
double function_2(std::string s);

fmap(function_2, function_1);

错误是:

note: candidate template ignored: could not match 'function<type-parameter-0-1 (type-parameter-0-0)>' against 'double (std::__1::basic_string<char>)'

B fmap(const std::function<B(A)> &funcA, const std::function<A(R)> &funcR) {

fmap函数的正确实现方法是什么?

最佳答案

您可以使用Template type deduction with std::function中的简洁模板转换技巧来做到这一点

#include <functional>
#include <iostream>
#include <string>
using namespace std;

template<class T>
struct AsFunction
    : public AsFunction<decltype(&T::operator())>
{};

template<class ReturnType, class... Args>
struct AsFunction<ReturnType(Args...)> {
    using type = std::function<ReturnType(Args...)>;
};

template<class ReturnType, class... Args>
struct AsFunction<ReturnType(*)(Args...)> {
    using type = std::function<ReturnType(Args...)>;
};


template<class Class, class ReturnType, class... Args>
struct AsFunction<ReturnType(Class::*)(Args...) const> {
    using type = std::function<ReturnType(Args...)>;
};

template<class F>
auto toFunction(F f) -> typename AsFunction<F>::type {
    return { f };
}

template<class A, class B, class R>
B fmap(const std::function<B(A)>& funcA, const std::function<A(R)>& funcR, R value) {
    return funcA(funcR(value));
}

template <class T>
auto ToFunction(T t) {
    return t;
}

std::string function_1(int n) {
    return ""s;
}

double function_2(std::string s) {
    return 0.0;
}

int main() {
    fmap(toFunction(function_2), toFunction(function_1), 5);
    return 0;
}

关于c++ - C++ 中的 Reader 仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649561/

相关文章:

c++ - 我可以在任何平台上运行 C 和 C++ 吗?

c++ - 使用线程在python中调用多个c++函数

c++ - 如何使用(类似?)可变参数模板在 C++14 中编写位掩码

c++ - 用于 future 派生类型的基本模板类型的模板特化

c++ - 阅读堆栈/堆和符号表概念的好资源是什么?

c++ - 如何将协变返回类型与智能指针一起使用?

c++ - 将唯一指针传递给模板函数

haskell - 将 "Just []"变为 "Nothing"

rest - Haskell Yesod - 执行 POST 请求时浏览器 OPTIONS 请求的 CORS 问题

haskell - monad 中的可变参数函数