我有一个可变参数模板类,用于保留自己的网络类的答案
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;它会在许多具有不同回复签名的项目中使用。有什么方法可以保留这些类型并在将来进行添加而无需完全重构?我曾考虑过某种经理阶层,但我可能会想得太多
答案 0 :(得分:1)
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::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;
}