我有以下情况:
template <typename T>
class Derived
{
public:
T m_Data;
};
And I need to store them in std::vector
so I've introduced an abstract parent class like so:
class Base
{
public:
virtual unsigned int GetID() const = 0;
};
And made Derived
inherit from Base
:
template <typename T>
class Derived : public Base
{
public:
T m_Data;
unsigned int GetID() const override
{
return something;
}
}
So now I can store them in std::vector
like so:
std::vector<Base*> m_Bases;
Now at some point of program execution I need to iterate over m_Bases
and select a few based on some condition and use their respective m_Data
like so:
void Foo()
{
for (auto& b : m_Bases)
{
if (some_condition)
{
// Access b->m_Data
}
}
}
Since I can't do that because T m_Data
is member of Derived
and not Base
, I introduces a visitor vector:
std::vector<std::function<void(Base*, std::function<void(std::any)>&)>> m_DerivedVisitors;
Now when I insert a new Derived<T>
to m_Bases
I also insert a new lambda to m_DerivedVisitors
so I could call later like so:
template <typename T>
void CreateBase()
m_Bases.push_back(new Derived<T>());
m_DerivedVisitors.push_back([](Base* base, auto visitor)
{
if (dynamic_cast<Derived<T>*>(base) != nullptr)
{
visitor(static_cast<Derived<T>*>(base));
}
});
Now Foo
could potentially get a Derived
instance in a visitor generic lambda (I hope) like so:
void Foo()
{
for (auto& b : m_Bases)
{
if (some_condition)
{
// Access b->m_Data
// Note that I made sure GetID() is returning counting index based on template instantiation
// So I could use it to index into m_Bases as-well as into m_DerivedVisitors
m_DerivedVisitors[b->GetID()](base, [&](auto derivedPtr) {
// Now I can access derivedPtr->m_Data and use outside variable with capture list
});
}
}
}
Now if you have sharp eyes you can see I have a few problems with this code.
I don't know what type the second argument of m_DerivedVisitors
should be.
Right now it's set to std::function<void(std::any)>&
because I do not know the type of the visitor because it's argument supposed to be the Derived
template type so I tried to use std::any
and for the visitor it-self I used an auto
parameter making it a generic lambda:
std::vector<std::function<void(Base*, std::function<void(std::any)>&)>> m_DerivedVisitors;
...
m_DerivedVisitors[b->GetID()](base, [&](auto derivedPtr) {
// Now I can access derivedPtr->m_Data and use outside variable with capture list
});
...
我不确定如何使它工作。 如果有人可以通过代码示例解释如何做到这一点,我将不胜感激。
提前致谢。