Templated multistack implementation - how?

烈酒焚心 提交于 2021-02-11 15:48:34

问题


I need a 'MultiStack' taking different types of objects, putting each type in a separate stack.

This is what it looks like so far. The open problem is: how to handle the containers for a number of different T

class MultiStack
{

public:

    template<typename T>
    const T& Get()
    {
        return Container<T>.back();
    }

    template<typename T>
    void Push( const T& t )
    {
        Container<T>.push_back( t );
    }

    template<typename T>
    void Pop( const T& /*t*/ )
    {
        Container<T>.pop_back();
    }

private:

    // this does not make sense, we obv. need one stack for each T
    // template<typename T>
    // std::vector<T>           Container;

};

Now, I could use the old trick, putting the Container in a member function, like

template<typename T>
auto GetContainer()
{
    static std::vector<T> C;
    return C;
}

but I don't like this anymore in the age of multi-threading. It is 'dangerous', right!?

Is there a better, elegant way? It is conceivable that I know the allowed types beforehand, if that helps realizing it.


回答1:


but I don't like this anymore in the age of multi-threading. It is 'dangerous', right!?

Issue is not multi-threading. initialization would be fine. You still have to protect/synchronize access though, as regular multi-threading code.

Issue is that the container is not per instance of MultiTask, as it is static. It is mostly as if MultiTask were a Singleton.

It is conceivable that I know the allowed types beforehand, if that helps realizing it.

That helps, you can then use std::tuple, something like (C++14):

template <typename ... Ts>
class MultiStack
{
public:
    template<typename T>
    const T& Get() const
    {
        return GetContainer<T>().back();
    }

    template<typename T>
    void Push(const T& t)
    {
        GetContainer<T>().push_back(t);
    }

    template <typename T>
    void Pop()
    {
        GetContainer<T>().pop_back();
    }

private:
    template <typename T>
    const std::vector<T>& GetContainer() const { return std::get<std::vector<T>>(Containers); }
    template <typename T>
    std::vector<T>& GetContainer() { return std::get<std::vector<T>>(Containers); }

private:
    std::tuple<std::vector<Ts>...> Containers;
};


来源:https://stackoverflow.com/questions/61299941/templated-multistack-implementation-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!