static key map initialization

I am having a terible time with static key map initialization.
I read many examples by searching: c++11 static key map initialization
The following example is based on post by mfontanini from
http://stackoverflow.com/questions/13464325/static-map-initialization

Please tell me why the following example won't compile.
I am using gcc version 4.8.1
GCC 4.8.1 is C++11 feature-complete http://gcc.gnu.org/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <map>

class A
{
	private:
		const int key;
	public:
		typedef std::map<int, char> KeyMap; 
		static KeyMap km;

		A(const int k): key(k) { };
		char getChar() { return km[key]; };
};
// initialize static map out of class
A::KeyMap A::km = {{1, 'a'}, {2, 'b'}};

int main()
{
	A a(1);

	std::cout << a.getChar(); // expect to print 'a'
}

Thank you.
Compiles for me.
$ g++ --version
g++ (Debian 4.8.2-10) 4.8.2


What errors do you get?
Thanks for reminding me norm, compile error occurs on line 16 above:

D:\wolf\Documents\teensy\demo_MinGW>g++ temp2.cpp
temp2.cpp:16:38: error: in C++98 'A::km' must be initialized by constructor, not
 by '{...}'
 A::KeyMap A::km = {{1, 'a'}, {2, 'b'}};
                                      ^
temp2.cpp:16:38: warning: extended initializer lists only available with -std=c+
+11 or -std=gnu++11 [enabled by default]
temp2.cpp:16:38: error: could not convert '{{1, 'a'}, {2, 'b'}}' from '<brace-en
closed initializer list>' to 'A::KeyMap {aka std::map<int, char>}'


mingw gcc version 4.8.1 (GCC):
D:\keybrd_test\emulate_Arduino>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.8.1/configure --prefix=/mingw --host=mingw32 --build=m
ingw32 --without-pic --enable-shared --enable-static --with-gnu-ld --enable-lto
--enable-libssp --disable-multilib --enable-languages=c,c++,fortran,objc,obj-c++
,ada --disable-sjlj-exceptions --with-dwarf2 --disable-win32-registry --enable-l
ibstdcxx-debug --enable-version-specific-runtime-libs --with-gmp=/usr/src/pkg/gm
p-5.1.2-1-mingw32-src/bld --with-mpc=/usr/src/pkg/mpc-1.0.1-1-mingw32-src/bld --
with-mpfr= --with-system-zlib --with-gnu-as --enable-decimal-float=yes --enable-
libgomp --enable-threads --with-libiconv-prefix=/mingw32 --with-libintl-prefix=/
mingw
Thread model: win32
gcc version 4.8.1 (GCC)
Last edited on
You need to pass -std=c++11 to the compiler.
g++ -std=c++11 temp2.cpp




Edit: Changed wording.
Last edited on
That fixed it. Thank you so much norm!!! You saved my day.
You're welcome.

The "[enabled by default]" part of that warning is confusing!
Topic archived. No new replies allowed.