【发布时间】:2016-06-06 14:17:41
【问题描述】:
我有以下模板函数:
template <class T>
inline T ParseValueFromJson(const JSONValue& jsonValue);
在其他模板函数中依次使用,例如:
template <class T>
bool TryGetValueFromJson(
const JSONValue& jsonValue,
const String& name,
T& variable)
{
if (!jsonValue.Contains(name))
{
return false;
}
variable = ParseValueFromJson<T>(jsonValue[name]);
return true;
}
现在我想将 ParseValueFromJson 专门用于许多不同的类型,其中之一是模板类(Vector)。然而,使用典型的特化意味着 Vector 的类型参数将是未定义的:
template <>
inline Vector<T> ParseValueFromJson<Vector<T>>(const JSONValue& jsonValue)
除此之外,在函数实现中我需要 T 的类型,因为我将使用 ParseValueFromJson 的 T 类型版本来解析单个项目。
当然,如果我在特化中使用模板 T,它是一个不同的函数,会导致模棱两可的调用:
template <typename T>
inline Vector<T> ParseValueFromJson<Vector<T>>(const JSONValue& jsonValue)
那么这可能吗,还是我需要选择一个单独的 TryGetContainerFromJson(或类似)函数,将模板化集合类型作为第二个模板参数?
【问题讨论】: