我不知道如何准确地写这个问题的标题...
我有这样的课:
class HasFuncBase
{
public:
virtual int GetKey() = 0;
};
template<class... Cs>
class HasFunc : public HasFuncBase
{
public:
typedef std::function<void(std::vector<Cs>&....)> Func;
HasFunc(Func func)
:
m_func(func)
{}
virtual int GetKey() { return id; }
private:
Func m_func;
static int id;
};
template<class... Cs>
int HasFunc::id = unique_key_generator<Cs...>::GetKey();
I've skipped the unique_key_generator
for brevity.
然后,另一个类为上面的m_func保存“数据”:
class HasData
{
public:
std::vector<std::vector<char>> data;
int someId;
}
数据向量中的每个元素都是HasFunc类的数据字节。
另一类负责管理整个事情:
class Manager
{
public:
std::vector<HasData> m_hadDatas;
std::vector<HasFuncBase*> m_hasFuncs;
};
现在,Manager类需要为匹配的数据找到匹配的func并调用它们;
class Manager
...
void CallFuncs()
{
for(HasFuncBase* f : m_hasFuncs)
{
for(HasData& d : m_hasDatas)
{
if(d.someId == f->GetKey())
{
/*
I need to convert the vector of data vectors
in the HasData into function arguments
of the right type for HasFunc
*/
}
}
}
}
...
我知道我可以向HasFunc类添加模板函数,例如:
class HasClass
...
template<typename... Ts>
void Execute(std::vector<Ts>&... dataArrays)
{
m_func(dataArrays);
}
...
which seems to me to be the way to do it, because Manager
doesn't know the types of the concrete HasFuncBase
.
I figure I need some sort of template unpacking trick in HasClass
that will be called from Manager
that will then cast the vector<data>
arrays, after unpacking them, into the above Execute
function, but I can't see how.