1

I have a program that involves two different data structures, and so I created a class that acts as a generalized data structure that either of the original two can be represented as. (Because the next part of the program ideally only handles a single kind of data structure)

I implemented this generalized data structure with a template, because the main underlying data of one original data structure is a vector of doubles and for the other, a vector of unsigned ints. I wanted to keep these underlying data types in the generalized data structure.

I then declared two different constructors, one for each of the original data structures, that takes that original data struct as an input. I then created one template specialization for each constructor, as seen in the code below:

StatsInputData.cpp


template <> StatsInputData<double>::StatsInputData(const MetricData& outputMetricData)
{
    //transfer data from MetricData data structure to StatsInputData<double>
}

template <> StatsInputData<uint64_t>::StatsInputData(const OsPerfmon* osPerfmon)
{
    //transfer data from OsPerfmon data structure to StatsInputData<uint64_t>
}

StatsInputData.h


template <typename NumericType>

class StatsInputData
{
public:

    StatsInputData(const MetricData& outputMetricData);
    StatsInputData(const OsPerfmon* osPerfmon);
    //other methods and underlying data
};

template <> StatsInputData<double>::StatsInputData(const MetricData& outputMetricData);
template <> StatsInputData<uint64_t>::StatsInputData(const OsPerfmon* osPerfmon);

I heard from one programmer that in this situation, factory methods are the normal design pattern to use. I'm personally not sure how the factory method would be used in this situation. So I was wondering if others could see a downside to my implementation, and if the factory method could be used for a better implementation, how so.

1
  • 1
    Neither of these seems right to me. Nov 10 '20 at 10:22
1

Both templates and the factory pattern are not suited for that purpose. If you only have two different types of data structures in your program and don't plan on adding more soon, you shouldn't worry about generalizing because the simplest solution is best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.