alve89
alve89

Reputation: 999

Vector in static class

I'd like to have a static (const) vector in a static class. The vector wont be filled with new elements, it will only have the elements defined in class configuration: {1,2,3,4,5}.

How can I make the vector debugLevels static?

#include <ArduinoSTL.h>

class configuration {
  public:
  static std::vector<int> const debugLevels = {1,2,3,4,5}; // throws error: in-class initialization of static data member 'const std::vector<int> configuration::debugLevels' of incomplete type
};

void setup() {
  for(int i=0; i<configuration::debugLevels.size(); i++ {
    // do some stuff here...
  }
}

void loop() {
}

Upvotes: 0

Views: 240

Answers (3)

Kerek
Kerek

Reputation: 1110

In case that you need to use something similar, notice that the initialization should occur outside of the class definition (more specifically, in the corresponding .cpp file), meaning:

config.hpp:

class configuration 
{
  public:
  static const std::array<int, 5> debugLevels;
};

config.cpp:

const std::array<int, 5> configuration::debugLevels = {1,2,3,4,5};

As I have written above, probably the usage of std::array is better in this case, and I agree that if there is no need for a class functionality, you should use namespace instead.

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136256

std::vector doesn't seem to be warranted here. A min/max would do:

class configuration {
  public:
  static constexpr int debugLevelMin = 1;
  static constexpr int debugLevelMax = 5;
};

void setup() {
  for(int i=debugLevelMin; i<=debugLevelMax; i++ {
    // do some stuff here...
  }
}

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180510

The easiest thing to do is change your class into a namespace

namespace configuration {
  const std::vector<int> debugLevels = {1,2,3,4,5};
}

Upvotes: 5

Related Questions