gpt4 book ai didi

templates - C++ 中类似 Haskell 的 `const`

转载 作者:行者123 更新时间:2023-12-02 22:46:03 25 4
gpt4 key购买 nike

所以在过去的几周里,我一直在尝试用函数式编程类型解决 C++11 中的问题,时不时地,我会遇到这样的情况:我需要一个返回 a 的函数恒定值。

在Haskell中,有一个函数

const :: a -> b -> a
const x = \_ -> x

返回一个函数,该函数的计算结果为 const 的原始参数,无论提供给它什么参数。我想在 C++11 中创建类似的东西。这种结构对于表示函数中的特殊行为非常有用(发送到过滤器的常量 true 函数将使数据保持不变)。这是我的第一次尝试:

template<class T>
std::function<T(...)> constF(T x) {
return ([x](...) { return x; });
}

它可以自行编译,但任何使用它的尝试都会导致不完整类型的错误。我的第二次尝试是这样的:

template<class T, class... Args>
std::function<T(Args...)> constF(T x) {
return ([x](Args...) { return x; });
}

这更接近,但不允许我提供任何论据,除非我明确声明它们。

auto trueFunc1 = constF(true);
auto trueFunc2 = constF<bool, int>(true);
cout << trueFunc1() << endl; //works
cout << trueFunc1(12) << endl; //doesn't compile
cout << trueFunc2(12) << endl; //works

理想情况下,正确的构造不会在 trueFunc1 和 trueFunc2 之间产生任何差异。

这在 C++ 中可能吗?

最佳答案

由于 C++11 没有泛型或可变 lambda,我会编写一个仿函数模板类:

template <typename T>
// requires CopyConstructible<T>
class const_function {
T value;
public:
template <typename U, typename = typename std::enable_if<std::is_convertible<U,T>::value>::type>
const_function(U&& val) :
value(std::forward<U>(val)) {}

template <typename... Args>
T operator () (Args&&...) const {
return value;
}
};

还有一个很好的类型推导包装器来制作它们:

template <typename T>
const_function<typename std::remove_reference<T>::type>
constF(T&& t) {
return {std::forward<T>(t)};
}

在 C++1y 中,我认为简单的等价物是:

template <typename T>
auto constF(T&& t) {
return [t{std::forward<T>(t)}](auto&&...){return t;};
}

关于templates - C++ 中类似 Haskell 的 `const`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com