模板化多堆栈实现-怎么做?
我需要一个"MultiStack"来容纳不同类型的对象,并将每种类型放在单独的堆栈中.
I need a 'MultiStack' taking different types of objects, putting each type in a separate stack.
这是到目前为止的样子.开放的问题是:如何处理多个不同T的容器
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;
};
现在,我可以使用旧的技巧,将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.
但是在多线程时代,我不再喜欢这样.是危险",对!!
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.
问题是该容器不是每个 MultiTask
实例,因为它是静态的.多数情况下, MultiTask
是一个Singleton.
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.
那有帮助,然后您可以使用 std :: tuple
,类似(C ++ 14):
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;
};