Home > database >  Array initialization throwing a compiler error
Array initialization throwing a compiler error

Time:01-07

I'm trying to initialize an std::array based on the length of a variadic template. My code is posted below, I'd like the array to hold ints, with enough room to fit one int per parameter passed in Types.

The sizeof...() operator should do what I want, if I'm not mistaken, so I would think that the following code is valid.

#include <iostream>
#include <vector>


template<typename Type, typename ...Types>
class Object{
    public:
        std::array<int, sizeof...(Types)> loadedValues;
};



int main(){
    auto k = new Object<int, float, int, int>();
}

However, I'm running into a mysterious compiler error:

error: ‘Object<Type, Types>::values’ has incomplete type
std::array<int, sizeof...(Types)> values;

(GCC 12)

I'm still relatively new to metaprogramming, so it could just be an error in my code that I haven't caught, but if anyone could provide insight on why compilation is failing, that would be greatly appreciated!

CodePudding user response:

Forgetting to include the header array will result in an incomplete type error. Although GCC 12.2 issues a warning:

<source>:1:1: note: 'std::array' is defined in header '<array>'; did you forget to '#include <array>'?
      | #include <array>

As shown on Godbolt here: https://godbolt.org/z/6nfTTKre, however, this may be obscured or harder to find if there are a number of templates (My case), and there is a long list of errors/warnings, or depending on your settings.

I wrote this question before checking Godbolt, which revealed the error quite quickly, so I figured a Q&A style question would be appropriate should anyone run into a similar error.

  • Related