c++ - 如何使用概念将参数传递给类方法?

标签 c++ c++20 c++-concepts c++-templates

我有一个从 std::optional 类继承的 optional_monadic 类

    template <class T>
    class monadic_optional : public std::optional<T>
    {
    public:
      using std::optional<T>::optional;
      monadic_optional(T value) : std::optional<T>(value) {}
    }

在这个类中我描述了方法

    template <class Return>
    nonstd::monadic_optional<Return> and_then(std::function<nonstd::monadic_optional<Return>(T)> func)
    {
     if (this->has_value())
        return func(this->value());
     else
        return std::nullopt;
    }

我想使用概念将模板传递给检查它是否是函数的方法。如何使用概念来实现这一点?

    template <class T>
    concept convertible_to_func = std::convertible_to <T, std::function<nonstd::monadic_optional<Return>(T)>>
    requires
    {
    };
    nonstd::monadic_optional<T> and_then(T func)
    {
     if (this->has_value())
        return func(this->value());
     else
        return std::nullopt;
    }

它应该看起来像这样,但它不能编译。

最佳答案

这对于 invokable 来说非常简单。而且您不必要求它成为 std::function:

auto and_then(std::invocable<T> auto func) ->
  monadic_optional<std::invoke_result_t<decltype(func), T>>
{
  if(this->has_value())
    return std::invoke(func, *this);
  return std::nullopt;
}

关于c++ - 如何使用概念将参数传递给类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72929159/

相关文章:

c++ - 通过隐式转换小于运算符?

C++20 概念 : Which template specialization gets chosen when the template argument qualifies for multiple concepts?

c++ - 检查创建的对象的类是否派生自另一个类

C++ 运算符 % 保证

c++ - 嵌套 co_await/coroutine 类似于 C# 嵌套等待风格

模块中的 C++ "Using"

c++ - 具有编译时间常量的模板化 Lambda 函数

c++ - 如何从概念中检索类型?

c++ - boost LNK2019 错误

c++ - 将数组中的两个字节解析为 uint16_t?