Passing a member function through std :: function

I want to check if the data field is valid (valid means that it is not null and not populated with the default value)

Primarily

return (!connector->IsNull(field_id) and connector->Get<type>Default(field_id, default_value))

But the "type" can be one of many types (string, int64, etc.), so there are 5-6 different functions. I made a helper function for it, and I'm trying to pass the corresponding GetDefault ...

template<typename T> bool IsValidField(std::unique_ptr<Connector>& connector, const std::function<T(int, T)> &GetDefault, int field_id, T default_value){
  return (!connector->IsNull(field_id) && connection->GetDefault(field_id, default_value) != default_value);
}

And I call the helper function with ....

IsValidField(connector, connector->GetStringWithDefault,20,"")

I get the error "error: the reference to the non-stationary member function must be called" because GetStringWithDefault is not a static function, how can I fix this?

Alternatively, is there a way to make it a little less uncomfortable?

0
3

: std::bind, std::mem_fn.


std::bind

template<typename T, typename F>
bool IsValidField(std::unique_ptr<Connector>& connector, F GetDefault,
                  int field_id, T default_value)
{
    return (!connector->IsNull(field_id) &&
            GetDefault(field_id, default_value) != default_value);
}

IsValidField(

IsValidField(connector,
             std::bind(&ClassForConnector::GetStringWithDefault, _1, _2),
             20,"");

std::mem_fn -

template<typename T, typename F>
bool IsValidField(std::unique_ptr<Connector>& connector, F GetDefault,
                  int field_id, T default_value)
{
    return (!connector->IsNull(field_id) &&
            GetDefault(connector, field_id, default_value) != default_value);
}

IsValidField(connector,
             std::mem_fn(&ClassForConnector::GetStringWithDefault),
             20,"");
+1

, , , , , :

IsValidField(connector, [connector]() -> T {return connector->GetStringWithDefault(20, "")})

IsValidField.

+1

. .

GetStringWithDefault, -, , , :

namespace impl {
  template<class T, T Connector::*Method(int, T const&)>
  struct GetWithDefault {
    T operator()(Connector const& connector, int id, T const& default) const {
      return (connector.*Method)(id, default);
  };
}

template<class T>
struct GetWithDefault;

template<>struct GetWithDefault<std::string>:
  impl::GetWithDefault<std::string, &Connector::GetStringWithDefault>
{};

. GetWithDefault<Bob>{}(*connector, id, default_bob) , .

:

template<class T>
bool IsValidField(Connector const& connector, int id, T const& default_value) {
    return !connector.IsNull(id) && (GetWithDefault<T>{}(connector, id, default_value)!=default_value);
  }
};

This moves the connection between Tand gettor to a helper type GetWithDefault, where we implement it using explicit specialization (like a feature class).

0
source

Source: https://habr.com/ru/post/1654230/


All Articles