我试图找出如何迭代在内存中连续共享公共基本父类的对象的容器(如std :: vector).
为了演示这个问题,让我们使用以下示例.
class Base
{
public:
Base();
virtual void doStuff() = 0;
};
class DerivedA : public Base
{
private:
//specific A member variables
public:
DerivedA();
virtual void doStuff();
};
class DerivedB : public Base
{
private:
//specific B member variables
public:
DerivedB();
virtual void doStuff();
};
Run Code Online (Sandbox Code Playgroud)
现在,使用std :: vector进行迭代会将对象保留在连续的内存中,但是由于没有派生属性的空间,我们会遇到切片.
所以我们必须使用像这样的指针的多态技术
int main ()
{
std::vector<Base*> container;
container.push_back(new DerivedA());
container.push_back(new DerivedB());
for (std::vector<Base*>::iterator i = container.begin(); i!=container.end(); i++)
{
(*(*i)).doStuff();
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,应该可以正常工作,因为这些类已经实现了.
问题: 现在,向量包含连续内存中的指针,但这并不意味着它们指向的地址是.
因此,如果我希望能够随时在对象中删除和插入对象,则对象将遍布内存中的所有位置. …
问题.
我是模板元编程的新手,并且不确定如何在元组上实现类型过滤转换,其中在提供过滤描述时生成类型.我相信以下代码段演示了我想要的行为.
enum : int {
INCLUDE,
EXCLUDE
};
template <int filter_val, class T>
struct filter {
};
int
main() {
struct A {};
struct B {};
struct C {};
typedef std::tuple<filter<INCLUDE, A>,
filter<EXCLUDE, B>,
filter<INCLUDE, C>> filters;
typedef filter_all<filters>::type filtered;
static_assert(std::is_same<filtered,
std::tuple<A, C>
>::value,
":(");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试过的
据我所知,你不能解包超过1个独立的可变参数模板,所以我想解决问题的方法是在递归模板专业化过程中维护两个元组,其中一个代表我们在递归中的位置,而另一个代表所谓的递归 - 包括T的.
template <template <class ...> class, class ...Unfiltered_Ts>
struct filter_all {
private:
template <class Unfiltered_Ts_Tuple, class Included_Ts_Tuple>
struct filter_all_impl;
// CASE 1: Include T in the result
template …Run Code Online (Sandbox Code Playgroud)