【发布时间】:2019-10-18 08:15:34
【问题描述】:
我有这个函数模板:
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
如何消除这种歧义?
【问题讨论】:
-
您没有显示进行调用的代码。
-
@keith 我认为现在我想做什么更清楚了。
标签: c++ c++11 templates sfinae