简体   繁体   中英

Fixed-sized C arrays with template parameter-dependent sizes

I am working with a templated class, which I'd like to include fixed-sized data arrays whose size depends on the template parameter. A simplified example is

template<int D>
class Foo
{    
    private:
        int m_array[D*(D+1)];            
};

While variable-sized C arrays are understandably frowned upon in general, here they might be justifiable, since D is small and it's nice and clear how many values m_array holds (and that it cannot change size). My questions are

  1. Is this in fact a justifiable use of variable-sized arrays in the first place?
  2. Is this always bad practice, as these arrays are not universally supported by compilers?
  3. Is there a clean alternative? One could use a std::vector and set the size in a constructor, which I'd argue makes the code less clear. Would it be preferable to use C++11's std::array , thus changing the relevant line in the example above to std::array<int,D*(D+1)> m_array; ?

Your example isn't a variable-length array , like what exists in C99. There, the size of the array is only known at runtime.

Here, you use a compile-time constant to set the size of the array. There is no problem with doing so. Go forth and enjoy.

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