【发布时间】:2023-03-31 04:59:02
【问题描述】:
我正在尝试通过使用 C++ 模板来简化我之前的一些 JSON 序列化,以在一定程度上减少样板代码。一切都很好,直到我想序列化列表等类型,因为它们本身也是模板,并且似乎需要部分模板专业化,而模板函数似乎不存在。
因此,我应用了我在这里找到的一个巧妙的小技巧: https://www.fluentcpp.com/2017/08/15/function-templates-partial-specialization-cpp/
namespace Support {
// These are in header files
template <typename T>
struct convertType{};
// Specialised template that serialises a list by iterating over its members
template <typename T>
QJsonValue toJsonValue(const QList<T> &source, convertType<QList<T>>) {
QJsonArray result;
for (auto it = source.cbegin(); it != source.cend(); it++) {
result.push_back(*it);
}
return result;
}
// "Fallback" template that generates an assertion
template <typename T>
QJsonValue toJsonValue(const T &source, convertType<T>) {
// This function should never be called.
std::string msg = "toJsonValue called with unimplemented type ";
msg += typeid (T).name();
Q_ASSERT_X(false, "toJsonValue<T>", msg.c_str()); // Always asserts.
return QJsonValue();
}
// Convenience function
template<typename T>
QJsonValue toJsonValue(const T &source) {
return toJsonValue<T>(source, convertType<T>{});
}
// This one is in the CPP file
// Integer
template <>
QJsonValue toJsonValue(const int &source, convertType<int>) {
return QJsonValue(source);
}
} // NS Support
当我用一个整数调用这个模板时:
qDebug() << Support::toJsonValue<int>(3713); // if not familiar with Qt, think as qDebug() being the same as std::cout.
这会按预期输出“QJsonValue(double, 3713)”。
但是,当我尝试按如下方式传递列表时:
QList<int> foo = {1, 2, 3};
qDebug() << Support::toJsonValue<QList<int>>(foo);
在我看来,代码将采用最不专业的函数模板,即生成断言的模板。我不知道为什么会发生这种情况,因为我希望它会采用专门用于 QList 的函数模板。
有人知道为什么会这样吗?我是否可能滥用模板?
【问题讨论】:
标签: c++ templates overloading template-specialization template-argument-deduction