C ++ 11 standard initialization: field initializer is not constant

I am trying to create an instance of a rowset as follows:

class POI {
public:
...
  static const std::set<std::string> TYPES { "restaurant", "education", "financial", "health", "culture", "other" };
...
}

Now, when I do this, I get these errors (everything on this line):

error: field initializer is not constant
 static const std::set<std::string> TYPES { "restaurant", "education", "financial", "health", "culture", "other" };
error: in-class initialization of static data member 'const std::set<std::basic_string<char> > POI::TYPES' of non-literal type
error: non-constant in-class initialization invalid for static member 'POI::TYPES'                                                              
error: (an out of class initialization is required)
error: 'POI::TYPES' cannot be initialized by a non-constant expression when being declared

It would make sense to my eyes if I suggested that the lines inside the set are not considered const. Is this really a problem? Unfortunately, I cannot find a way to declare these lines inside the initializer as const. Is it possible?

+4
source share
2 answers

You must initialize your static variable outside the line, as in:

#include <set>
#include <string>

class POI {
public:
  static const std::set<std::string> TYPES;
};
const std::set<std::string> POI::TYPES { "restaurant", "education", "financial", "health", "culture", "other" };

This will work for the integer / enum type, as specified in the standard (section 9.4.2 :)

const const const, , . .

+8

++ , . const enum . ++ 11 constexpr

[class.static.data]/3

, -, , (5.20). literal constexpr; , - -, -, . [...] , odr (3.2) ,

, , , out-of-line

class POI {
public:
  static const std::set<std::string> TYPES;
};

const std::set<std::string> POI::TYPES = {
   "restaurant", "education", "financial", "health", "culture", "other" 
};
+6

Source: https://habr.com/ru/post/1606212/


All Articles