Razzupaltuff
Razzupaltuff

Reputation: 2301

Pass initializer list to constructor?

I have written my own array template class "CArray" and want to pass something like { 1, 2, 3 } to one of its constructors so that I can create an array class instance "CArray a ( {1,2,3}, numElems );

However, I fail to find the proper syntax for the constructor.

template <class _T>
class CArray {
    public:
        _T* buffer;
        int length;

    CArray () : buffer (nullptr), length (0) {}

    void Create (int l) {
        buffer = new _T[length = l];
    }
       
    CArray (_T const* values, int numElems) {
        Create (numElems);
        memcpy (buffer, values, numElems * sizeof (_T));
    }
};

CArray<int> a = CArray<int>( {1,2,3}, 3 );

This neither works for MSVC 19 latest nor gcc 11.2. How would I have to write my constructor to make this work?

Is there a possibility to omit the "numElems" parameter and get the initializer length (elem count) from the compiler?

Upvotes: 1

Views: 571

Answers (1)

cigien
cigien

Reputation: 60208

Yes, the compiler can deduce the size of the brace-init list, if the argument is a reference to an array:

template<int numElems> 
CArray (_T const (&values)[numElems]) 
{
   // ...
}

and an object is created like this:

CArray<int> a = CArray<int>({1,2,3});

demo

Upvotes: 2

Related Questions