I have an eager project in which I try to enable serialization of structs as effortlessly as possible by writing something along the lines of this:
class Data {
const QString& string();
void setString(QString string);
...
};
const QString stringName() { return "string"; }
template class <class Invokee, typename ContentType, const QString(*NameFunction)(), const ContentType& (Invokee::* Getter)() const> Field;
void serialize() {
Data data{...};
QJsonObject serialized
= serialize<Data, Field1, Field2, ...>;
}
which should output a json object. I recently found out there are variadic templates in c++ and was very excited to see if I could define such a Serializer template that takes an arbitrary amount of Fields and then serializes them. However I was stuck at the following code:
template<
class Invokee,
typename ContentType,
const QString(*NameFunction)(),
const ContentType& (Invokee::* Getter)() const
>
void serializeToObject(QJsonObject& object, const Invokee& invokee) {
auto name = NameFunction();
object[name] = (invokee.*Getter)();
}
template<
class Invokee,
template<
class,
typename ContentType,
const QString(*)(),
const ContentType& (Invokee::* Getter)() const
> class Field,
class FieldClass,
class FieldInvokee,
typename FieldContentType,
const QString(*FieldNameFunction)(),
const FieldContentType& (Invokee::* FieldGetter)() const,
class... Args
>
void serializeToObject(QJsonObject& object, const Invokee& invokee) {
serializeToObject<FieldInvokee, FieldContentType, FieldNameFunction, FieldGetter>(object, invokee);
serializeToObject<Invokee, Args...>(object, invokee);
}
This appears to compile but I have not yet been able to get it to work in practice. Namely I am trying to use it like this:
void tryOut() {
Data data;
data.setString("testString");
QJsonObject object{};
serializeToObject
<
Data,
Field<Data, QString, stringName, &Data::string>
>
(object, testClass);
}
Compiler complains that my call to stringName is ill-formed. Despite that a test instantiation of Field<...> seems to work, the call to the function does not with error code:
candidate template ignored: couldn't infer template argument 'NameFunction'
void serializeToObject(QJsonObject& object, Invokee& invokee) {
I'm scratching my head as to what I'm doing wrong or if this is possible at all.