So, I'm still working on my matrix class (in case anyone reading this also read my thread from the other day). I really like the array-feature that I can initialize an array with a list of numbers, such as

double array[2]={1,2};

and would like to implement that in my matrix class as well. So far I have overloaded my operator= to accept an array of doubles, but that still means that I need to use two lines, first making an array, and then feeding it to my matrix. Does the {, , ,}-structure have a type?

In other words, what I have right now is

cMatrix& operator= (const double* array)

(with cMatrix being my matrix class). How should I change that definition to make it accept the {, , ,} directly?

Help will be much appreciated =)

>How should I change that definition to make it accept the {, , ,} directly?
Use a different language that supports such an overload or wait until C++0x comes out? You certainly have options, but the array initialization list isn't one of them. Your best option presently, in my opinion, is the iterator pattern found in the standard library:

cMatrix(Iterator first, Iterator last);

Then you can kind of cheat with an array to get a similar effect at the cost of an extra object:

double array[2]={1,2};
cMatrix mat(array, array + 2);

And if your matrix meets the basic sequence container requirements, you can use the standard library functions that work with containers.

Another (less recommended) alternative is setting up a constructor with a variable number of arguments:

#include <algorithm>
#include <cstdarg>
#include <iostream>

template <int N>
class Array {
    int _base[N];
    std::size_t _size;
    Array(std::size_t n, ...)
        va_list args;
        va_start(args, n);

        std::size_t i;

        // Fill in the "initializer" values
        for (i = 0; i < N && i < n; i++)
            _base[i] = va_arg(args, int);

        // Pad if size() > n
        while (i < N)
            _base[i++] = 0;


    std::size_t size() { return N; }
    int& operator[](std::size_t i) { return _base[i]; }

int main()
    Array<10> a(5, 1, 2, 3, 4, 5);

    for (std::size_t i = 0; i < a.size(); i++)
        std::cout<< a[i] <<'\n';

It's trickier to do safely and slightly awkward, but probably the closest you'll get to an initialization list prior to C++0x (without some serious template trickery). You might also want to take a look at the Boost library. Boost::Assign is one attempt to create a library for what you want.

Edited 6 Years Ago by Narue: n/a

hmm, your first solution is pretty much the same as my own, and I agree that the second would be asking for trouble. I guess I'll just stick with the two-liner then =)


This article has been dead for over six months. Start a new discussion instead.