8

My initialisation of a static const set<string> appears to be incorrect, I'd appreciate your guidelines on this:

obj.h:

class obj
{
  ...

private:
  static const set<string> keywords;
  ...

}

obj.cpp:

const string kw[] = {"GTR","LTR","LEQ","GEQ","NEQ","SQRT","sqrt"};
const set<string> obj::keywords = (kw,kw + sizeof(kw)/sizeof(kw[0]));

But this yields the error: error: conversion from ‘const string* {aka const std::basic_string<char>*}’ to non-scalar type ‘const std::set<std::basic_string<char> >’ requested

Can somebody tell me the correct way to initialise this set?

Prem
  • 3,373
  • 7
  • 29
  • 43

4 Answers4

24

I'm wondering why you're using an array to initialize the std::set.

You could directly initialize the set as:

const set<string> obj::keywords {"GTR","LTR","LEQ","GEQ","NEQ","SQRT","sqrt"};

That is what you should be doing if you're using a compiler supporting C++11.


As for what is wrong with your code, as the other two answers says, remove =:

const string kw[] = {"GTR","LTR","LEQ","GEQ","NEQ","SQRT","sqrt"};
const set<string> obj::keywords(kw,kw + sizeof(kw)/sizeof(kw[0]));

Hope that helps.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 2
    I very much agree. I kind of assumed it was C++03, but this is still valuable for others even if the OP is using C++03. Also, it might be worth noting that out of the main three, it's only MSVC that doesn't have the proper initializer list constructors yet. – chris May 03 '13 at 04:16
6

Take out the =. Just invoke the constructor.

const set<string> obj::keywords (kw,kw + sizeof(kw)/sizeof(kw[0]));
paddy
  • 60,864
  • 6
  • 61
  • 103
2

You need to remove the equals sign:

const set<string> obj::keywords(kw,kw + sizeof(kw)/sizeof(kw[0]));

What's happening is the dreaded comma operator. First, it evaluates kw and throws away the result. Next, it evaluates kw + sizeof(kw)/sizeof(kw[0]) and tries to copy-initialize keywords with that.

chris
  • 60,560
  • 13
  • 143
  • 205
2

I wonder why no-one suggested boost::assign from <boost/assign/list_of.hpp>

static const set<string> keywords = boost::assign::list_of("GTR")("SQRT")("whatever you need");

This way is less typing, but has weird syntax, because every item is between parentheses and there is no comma.


If you are using C++11 it is better use the way Nawaz suggested in his answer. My answer just shown another possible method and (in my opinion) better option for old standard.

Community
  • 1
  • 1
ST3
  • 8,826
  • 3
  • 68
  • 92