c++ - 使接受可选的函数接受非可选的函数?

标签 c++ templates c++17 option-type template-argument-deduction

我正在尝试以 monad 风格编写语法糖,超过 std::optional .请考虑:

template<class T>
void f(std::optional<T>)
{}

按原样,不能使用非可选的 T 调用此函数1(例如 int ),即使存在来自 T 的转换至std::optional<T> 2.

有没有办法制作f接受 std::optional<T>T (在调用者站点转换为可选),没有定义重载3?


1) f(0) : error: no matching function for call to 'f(int)'note: template argument deduction/substitution failed , ( demo ).
2) 因为模板参数推导不考虑转换。
3) 重载对于一元函数是一种可接受的解决方案,但是当你有像 operator+(optional, optional) 这样的二元函数时,它就开始令人烦恼了。 ,并且对于三元、四元、函数来说很痛苦。

最佳答案

另一个版本。这个不涉及任何内容:

template <typename T>
void f(T&& t) {
    std::optional opt = std::forward<T>(t);
}

类模板参数推导在这里已经做了正确的事情。如果 toptional,则复制扣除候选者将是首选,我们将返回相同的类型。否则,我们将其包装起来。

关于c++ - 使接受可选的函数接受非可选的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945067/

相关文章:

c++ - CppCMS 教程 : Linking template statically error: "fatal error: content.h: No such file or directory"

c++ - 你如何在 C++ 中实现协程

c++ - 我可以有一个要实例化的模板列表,而无需事先实例化吗?

c++ - 接受 std::vector<T> 或 std::array<T> 的模板类

c++ - 创建一个连续的动态矩阵

c++ - MPI 计算在多核上比在单核上错误

c++ - 在 C++ 中反转字符串时出现意外输出

c++ - 在 C++ 中传递函数指针

templates - Magento cms 页面渲染 {{ }} 变量

c++ - 编译模板