开发者

How do you handle this problem (Interface + template + reuse code)

开发者 https://www.devze.com 2023-02-04 09:46 出处:网络
Sorry for the odd topic, but didn\'t know how to exactly synthesize my question. Here is the problem:

Sorry for the odd topic, but didn't know how to exactly synthesize my question. Here is the problem:

I have a set of classes that will contain a std::vector of a type. It is a good candidate for templatizing just like:

template <typename T>
class Container
{
    T createObject() { T* obj=new T; _objects.push_back(obj); }
    std::vector<T> _objects;
}

The problem comes when I need this containers to be stored in a heterogenous map. They are a template so they do not exi开发者_开发百科st until initialization. I have thought about making Container derive from a dummy IContainer to have a good starting point, but as you see createObject needs to be templatized, so I could add IContainers to the hetrogenous map, but I won't be able to call createObject() and don't feel like doing a static_cast. Could anybody suggest a solution for this?

Thanks in advance, Amaral.


It sounds like you might be after something like boost::any. See http://www.boost.org/doc/libs/1_49_0/doc/html/any/s02.html

To summarize:

class Container
{
    std::vector<boost::any> _objects;

public:   
    template <class T>
    void Add(const T& t) { _objects.push_back(t); }
}

You would no longer need to template the class, in your case, just the Add function.

Be aware that it becomes difficult to work with the objects in the vector because you don't know what type they are - any time you want to use them you have to test to see what type it is.

You need to better explain what you are trying to do - but I would guess you do not want to actually use boost::any.

0

精彩评论

暂无评论...
验证码 换一张
取 消