C ++异构容器,以类型获取条目 [英] c++ heterogeneous container, get entry as type

查看:85
本文介绍了C ++异构容器,以类型获取条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的异构容器实现:

I have the following simple implementation of a Heterogeneous container:

struct Container {
    struct HolderBase {
    };

    template<typename S>
    struct Holder : HolderBase {
        Holder(S* s) : s_(s) {}
        S* s_;
    };

    template<typename S>
    void push_back(S* s) {
        h_.push_back(new Holder<S>(s));
    }

    vector<HolderBase*> h_;

    template<typename B>
    B* get(int i) {
        //magic here
    }
};

使用方法如下:

struct ElementBase {};
struct Element : ElementBase {};

int main()
{
    Container container;
    container.push_back(new Element);
    ElementBase* elementBase = container.get<ElementBase>(0);
}

我可以向其中添加任何类型的条目。但是我不知道如何实现一个函数来检索某种类型的元素,它可能与条目或基类相同。

I can add entries of any type to it. But I can't figure out how to implement a function to retrieve elements, as some type, which may be the same as the entry or a base class to it.

我需要的似乎同时是虚拟的和模板的,这是不可能的。

What I need seems to be both virtual and template at the same time, which is not possible.

推荐答案

似乎没有可能会完全准确地获得您想要的内容,而不会带来很多麻烦和麻烦(例如,在某种中央存储库中注册要使用的所有类)。

It doesn't seem possible to have exactly what you want without much pain and inconvenience (for example, registering all classes you want to work with in some kind of central repository).

这是一种几乎可以完成 的方法,可能会有用。

Here's one way to do almost what you want that can perhaps be useful.

class HolderBase
{
  public:
    virtual ~HolderBase() = default;    
    template <class X> X* get() { return dynamic_cast<X*>(this); }
};

template <class T>
class Holder : public HolderBase, public T
{
  public:
    using T::T;
};

然后,您的容器就是 vector< unique_ptr< HolderBase>> 或您喜欢的任何指针。

Your container is then just a vector<unique_ptr<HolderBase>> or whatever bunch-of-pointers you fancy.

测试驱动器:

struct A {
    virtual ~A() = default;
    A(int a) : a(a) {};
    int a;
};

struct B : A {
    B(int a, int b) : A(a), b(b) {};
    int b;
};

struct C : A {
    C(int a, int c) : A(a), c(c) {};
    int c;
};


int main () {
    std::vector<std::unique_ptr<HolderBase>> v;
    v.emplace_back(std::make_unique<Holder<B>>(7,40));
    v.emplace_back(std::make_unique<Holder<C>>(0,42));

    A* a = v[0]->template get<A>();
    B* b = v[0]->template get<B>();
    C* c = v[0]->template get<C>();

    std::cout << a << " " << b << " " << c << "\n";

    a = v[1]->template get<A>();
    b = v[1]->template get<B>();
    c = v[1]->template get<C>();

    std::cout << a << " " << b << " " << c << "\n";
}

这篇关于C ++异构容器,以类型获取条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆