[C ++ 11函数模板专门存在于类方法中]

问题描述 投票:1回答:1

我有此功能模板:

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

Tint时,专业化很简单:

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

但是,对于更复杂的类,我希望它调用存在的方法:

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

例如,对于类foo

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

我想给每个班级打电话:

int x_int;
write_json(x_int);
foo x_foo;
write_json(x_foo);

但是,我得到了:

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

如何消除这种歧义?

c++ c++11 templates sfinae
1个回答
2
投票

您也应该在另一个重载上应用SFINAE,以避免在类型T具有方法write_json时产生歧义。

© www.soinside.com 2019 - 2024. All rights reserved.