Home > Software design >  C const std::array size from constructor
C const std::array size from constructor

Time:11-15

Say I get an int from a lambda function ran at initialization of a class object. Is it possible to use that int to define the size of a std::array? Something like the following code.

#include <array>
#include <vector>
#include <iostream>

class Test1 {

    public:
        Test1( std::vector<int> vec1 ) :
            nvars([&vec1]() -> int { return vec1.size() 1; }())
        {
        };

        const int nvars;
        // ******This isn't allowed!!!!!!!!!
        const std::array<int,nvars> arr;
};

int main() {
    std::vector<int> vec{1,2,3,4};
    Test1 test1(vec);
    std::cout << "nvars: " << test1.nvars << std::endl;

    return 0;
}

I am a C beginner so any other advice will be welcome.

CodePudding user response:

No. The size of the array is part of its type. You cannot let it be determined at runtime.

You can have it be determined at compile time, if you do pass a std::array to the constructor. Since C 17 there is CTAD (class template argument deduction) which lets you write:

#include <array>


template <size_t N>
class Test1 {

    public:
        Test1( std::array<int,N> vec1 ) :
            arr(vec1)
        {
        };

        const std::array<int,N> arr;
};

int main() {
    std::array vec{1,2,3,4};
    Test1 test1(vec);
}

Live Demo

test1 is of type Test1<4>. Note that Test1<4> is a distinct different type than eg Test<5> or Test<24>. If you want one type to have a member array of different size, make it a std::vector.

  • Related