Search code examples
c++11c++14stdvector

calling std::vector::insert function in namespace or in header fails


I am trying to insert into a vector in a header file and it is not compiling for some reason.

#include <vector>
#include <inttypes.h>
#include <stdio.h>
    
namespace test
{
    std::vector<uint8_t> HEADERDATA{0x65, 0x73, 0x68, 0x00, 0x00, 0x00};
    std::vector<uint8_t> ADDITIONALDATA{0x00, 0x02, 0x00, 0x00};
    std::vector<uint8_t> DATA(HEADERDATA);
    DATA.insert(std::end(DATA), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
}

int main() {return 0;}

the compiler throws an error as:

<source>:15:1: error: 'DATA' does not name a type
   15 | DATA.insert(std::end(DATA),

However, if I move the insert into the main function, it works.

int main() 
{
    using namespace test;
    DATA.insert(std::end(DATA), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
}

Here is the link to godbolt.

Can someone explain this behavior?


Solution

  • It is not possible to write statements outside of a body of a function. Code can be run only from initializers, which is why the definition of the three variables works.

    You can use an in-line lambda to create and return the collection:

    namespace test
    {
        std::vector<uint8_t> HEADERDATA{0x65, 0x73, 0x68, 0x00, 0x00, 0x00};
        std::vector<uint8_t> ADDITIONALDATA{0x00, 0x02, 0x00, 0x00};
        std::vector<uint8_t> DATA([](){
            std::vector<uint8_t> data(HEADERDATA);
            data.insert(std::end(data), std::begin(ADDITIONALDATA), std::end(ADDITIONALDATA));
            return data;
        }());
    }