我有此功能模板:
template <class T>
Json::Value write_json(const T& object);
当T是int时,专业化很简单:
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
如何消除这种歧义?
您也应该在另一个重载上应用SFINAE,以避免在类型T
具有方法write_json
时产生歧义。