我有一个可变模板类,用于保存来自自己的网络类的答案
enum class TaskType {readReg, writeReg, readRnd, writeRnd, readBlock, writeBlock, pause};
template<typename... Args> class Reply {
public:
Reply(TaskType t, Args...params): t(t), tuple(std::make_tuple(params...)) {}
Reply();
TaskType t;
auto getData() const {return std::get<4>(tuple);} //simplified getter of safe function that deals with oversizing
private:
std::tuple<Args ...> tuple;
};
我注册模板签名以将其保存在Qvariant 中
using ReadRegReply = Reply<TaskType, uint, uint, uint, uint, uint> ;
using WriteReply = Reply<TaskType, uint, uint, uint> ;
using ReadRndReply = Reply<TaskType, uint, uint, uint, QVector<uint>, QVector<uint>> ;
using ReadBlockReply = Reply<TaskType, uint, uint, uint, uint, QVector<uint>> ;
Q_DECLARE_METATYPE(QVector<uint>)
Q_DECLARE_METATYPE(ReadRegReply)
Q_DECLARE_METATYPE(WriteReply)
Q_DECLARE_METATYPE(ReadRndReply)
Q_DECLARE_METATYPE(ReadBlockReply)
然后我这样处理它:
class Task: public QObject{
public:
//c-tor and some functions, virtual functions etc
template <class TReply> bool applyReply(TReply reply){
varReply = QVariant::fromValue(reply);
}
auto getData(){ //here I should return data from tuple inside reply.
QVariant::Type t = varReply.type();
auto l = varReply.value<t>();// t is not a constexp // t is not a reply type but enum QVariant::type, as I understand.
return l.getData(); // l has no method getData
}
QVariant varReply; //this is the qvariant that contains templated reply;
}
QVariant中有一些我怀念的东西。我认为注册类型应该以某种方式存储在Qvariant中,但事实并非如此。其他问题:我不能使用c++17;它将用于许多具有不同回复签名的项目。有没有一些方法可以保留这些类型,并在未来添加它们,而不需要完全重构?我想过某种经理课程,但我可能想得太多了
QVariant
只保存Qt中使用的内置类型的有用类型信息。如果你有其他类型,你需要在其他地方记录
class Task: public QObject{
public:
template <class TReply> bool applyReply(TReply reply){
varReply = QVariant::fromValue(reply);
}
template <class TReply> TReply getData(){reply.
return varReply.value<TReply>();
}
QVariant varReply;
}
void usesWriteTask() {
Task task;
task.applyReply(WriteReply());
// ...
WriteReply back = tast.getData<WriteReply>();
}
或者,如果你可以使用boost,你可以使用boost::variant
,这激发了std::variant
class Task: public QObject{
public:
using VarReply = boost::variant<ReadRegReply, WriteReply, ReadRndReply, ReadBlockReply>;
bool applyReply(VarReply reply) {
varReply = reply;
}
template <class Result> Result getData(boost::static_visitor<Result> & visitor) {
return varReply.apply_visitor(visitor);
}
VarReply varReply;
}