views:

72

answers:

1

I have a stream of data which is contained in a System::Collections::Queue. My data source can output the same data to multiple streams but to do so, needs to duplicate the data for each one. I currently do the following:

void DataGatherer::AddMyDataToQueues(MyData^ data)
{
    // Send duplicates to all queues
    for( int i = 0; i < m_outputQueues->Count; i++ )
    {
        AddResultToQueue(gcnew MyData(data), (Queue^)m_outputQueues[i]);
    }
}

Which works fine as long as I'm sending MyData objects. Lets say I want to send MyOtherData objects as well though. It would be nice to do something more generic like this:

void DataGatherer::AddDataToQueues(Object^ obj)
{
    // Send duplicates to all queues
    for( int i = 0; i < m_outputQueues->Count; i++ )
    {
        AddResultToQueue(gcnew Object(obj), (Queue^)m_outputQueues[i]);
    }
}

...but that won't compile because:

1>.\DataGatherer.cpp(72) : error C3673: 'System::Object' : class does not have a copy-constructor

So is it possible to duplicate an object without knowing its type? ..and if so, how do I do it? :)

+1  A: 

Have both MyData and MyOtherData implement ICloneable, then change AddDataToQueues to accept any object implementing ICloneable.

public ref class MyOtherData : public ICloneable
{
public:
    MyOtherData()
        : m_dummy(-1)
    {
    }

    virtual Object^ Clone()
    {
        MyOtherData ^clone = gcnew MyOtherData();
        clone->m_dummy = m_dummy;
        return clone;
    }

private:
    int m_dummy;
};

and then ...

void DataGatherer::AddDataToQueues(ICloneable^ data)
{
    // Send duplicates to all queues
    for( int i = 0; i < m_outputQueues->Count; i++ )
    {
        AddResultToQueue(data->Clone(), (Queue^)m_outputQueues[i]);
    }
}
mcdave
Looks good; I'll give it a shot :-)
Jon Cage