vendredi 18 octobre 2019

C++11 function template specializes as a class method if it exists

I have this function template:

template <class T>
Json::Value write_json(const T& object);

When T is an int, the specialization is simple:

template <>
Json::Value write_json(const int& object) {
  Json::Value output;
  output = object;
  return output;
};

However, for more complex classes, I want it to call a method if it exists:

template <typename T>
struct has_write_json_method {
    template <typename U>
    static constexpr decltype(std::declval<U>().write_json(), bool()) test(int) { return true; };

    template <typename U>
    static constexpr bool test(...) { return false; }

    static constexpr bool value = test<T>(int());
};

template <class T>
typename std::enable_if<has_write_json_method<T>::value, Json::Value>::type write_json(const T& object)  {
    object.write_json();
};

For instance, for class foo:

Json::Value foo::write_json(void) { 
  Json::Value output;
  output = 42;
  return output;
};

I got:

error: call of overloaded 'write_json(const foo&)' is ambiguous

How can I remove this ambiguity?

Aucun commentaire:

Enregistrer un commentaire