简体   繁体   中英

Variable number of arguments to constructor with variable types creating variable private member in C++

I have really heavy task to achieve and I haven't found any solution good enough. So, here is the description: - task is to evaluate multiple single dimension arrays which number can vary - good news is that it is possible to specify types of arrays

And desirable way of doing it: - creating a class with constructor that accepts variable number of arrays - these arrays should be also used as properties (private members), so multiple operations can be done on(with) them during lifecycle of object

How I tried to do it: - constructor member function with variable number of paramaters (I'm not sure why this doesn't work) - constructor with vector should be better way, but how to store arrays that type is specified in separate array, meaning you can't expect certain datatype for certain array in advance - I tried to declare variable number of arrays as private members with preprocessor, but it seems loops and other code do not work well inside private: declaration

Any idea from anybody?

constructor that accepts variable number of arrays:

vector< vector<T> > ?

the inner vectors can be of different sizes but must be of the same type.

constructor member function with variable number of parameters

You can use a function with variable number of parameters that creates a class, look at how boost::bind works, that takes lots of different parameter lists.

boost mpl may answer what you are trying to do, although it is rather unclear.

Why not use a simple parametrized class ?

If your compiler support C++0x you can also use initializer list for constructors with variable number of paramaters.

template<class ArrayType>
class ArrayContainer
{
   std::vector<ArrayType> m_arrays;

   public:
   ArrayContainer(std::initializer_list<ArrayType> arrays)
   {
     m_arrays.reserve(arrays.size());
     std::copy(arrays.begin(), arrays.end(), m_array);
   }
};

The constructor now accepts variable number of arrays.

auto container = new ArrayContainer({ a, b, c });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM