Initializer list with enum class

So the code does not compile because of cmd::a in the initializer list. How should one solve this?

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

enum class cmd : unsigned char 
{
  a=0x01,
  b=0x02,
  c=0x03
};

class test 
{
public:
  test(std::initializer_list<unsigned char> list):data(list){}
private:
  std::vector<unsigned char> data;
};


int main()
{
  test a({cmd::a,0x02,0x03});
}
In C++ 11 - there is no implicit (compiler supplied) conversion for
strongly typed enum ( enum class ) ro it's underlying type.

Which is a long winded way of saying that cmd::a will
not be automatically converted to unsigned char.

You can use static_cast test a({ static_cast<unsigned char>(cmd::a),0x02,0x03});
Another option is to not use enum class but then a, b and c will be visible in the global namespace. Too bad we cannot turn on/off implicit conversion and restricted scope separately.

If you are never going to use cmd as a type (only as a namespace) then you could put an anonymous enum inside a namespace named cmd. That way you get implicit conversion and you need to specify cmd:: to reach the enum values.

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

namespace cmd
{
	enum : unsigned char 
	{
		a=0x01,
		b=0x02,
		c=0x03
	};
}

class test 
{
public:
	test(std::initializer_list<unsigned char> list):data(list){}
private:
	std::vector<unsigned char> data;
};

int main()
{
	test a({cmd::a,0x02,0x03});
}
Last edited on
Thanks for the answers. I think I will go with Peter's answer as i wont realy need the cmd type and static cast will look longer and not so readable. :)
Topic archived. No new replies allowed.