问题描述
我想用一种方法将变量参数保存在缓存中,然后在另一种功能中使用它们。 想要在不使类“ X”成为模板类的情况下实现此目标,因为这意味着我需要将创建对象的方式的更改传播给许多链接方法。同样,如果X被模板化,则X的对象将变为不同的类型,并且不能保存在同一容器中。
我的首选方法是使“ bar”成为模板方法。因此只有相关的来电者需要更改。
我尝试了两种方法,一种方法是使用“ Ctx”类,由于在类级别尚不知道MsgType,因此我无法成为成员。另一种方法是使用variant的std :: vector。如何在运行时将参数推入向量? 还有其他方法吗?
#include<iostream>
#include<vector>
#include <tuple>
#include <variant>
template< typename ...MsgType>
struct Ctx {
void update(MsgType&& ... items) {
cache = std::make_tuple(std::forward<MsgType>(items)...);
}
std::tuple<MsgType...> cache;
};
struct X {
template<typename ...MsgType>
void bar(const int& y,MsgType&&... args) {
Ctx<T...> ctx;
ctx.update(std::forward<MsgType>(args)...);
//(vv.push_back(args)...);
}
void foo() {
//use 'args' saved from last call to 'bar'
}
//Ctx<...>
//std::vector<std::variant<uint16_t,uint8_t,uint32_t>> vv;
};
int main() {
X x; //want to avoid making the class 'X' a template class
x.bar(1,10.09,2121);
x.bar(2,10.229,2334); //Params to all call of bar for one instance of 'X' will have same number & type of args
x.foo();
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)