leemes
leemes

Reputation: 45675

Constant-sized vector class?

Is there a C++ standard type for holding a vector having a constant size? For example, something like a tuple with all element types being the same, so I only have to provide the size as a template argument?

I would like to have the same/similar behavior as when using std::vector, but the type should be as compact and efficient as a raw array (so no dynamic allocation, no run-time size information, etc.)

I prefer a C++03-compatible solution, so reusing a std::tuple isn't what I want.

Does the following class do what I want?

template<typename T, int N>
struct vec
{
    T component[N];

    // (+ some logic and accessors like operator[]...)
};

// concrete example:
vec<int,3> myVector;

Does it really differ from just saying T myVector[N] (concrete example int myVector[3])? Because that's what I am currently doing but I'm experiencing a couple of problems, since raw arrays are "just pointers" (+ size information) and can't be used as return values as well as aren't really passed by value (no deep copy occures).

Upvotes: 2

Views: 151

Answers (1)

MSalters
MSalters

Reputation: 179799

C++11 has std::array; which is basically the same as you wrote.

For C++03, use boost::array which is basically compatible to std::array.

Upvotes: 10

Related Questions