Home > Net >  How to use concepts to pass an argument to a class method?
How to use concepts to pass an argument to a class method?

Time:07-11

I have an optional_monadic class that I inherit from the std::optional class

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

In this class I describe the method

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

I want to use concepts to pass a template to a method that checks to see if it's a function. How can I implement this using concepts?

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

It should look something like this, but it doesn't compile.

CodePudding user response:

This is pretty trivial with invokable. And you don't have to require it to become a 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;
}
  • Related