Reputation: 9708
I want an array of binary messages in my code as literals. The messages are quite smal so I thought it would be easiest to use 'binary' literals. But how to do it?
I tried this code:
struct binary_message
{
binary_message(int size, unsigned char* bytes) : size_(size), bytes_(bytes) {}
int size_;
unsigned char* bytes_;
};
binary_message messages[] = {
{ 3, { 0x1, 0x2, 0x3 } },
{ 2, { 0x1, 0x2 } },
{ 1, { 0x1 } }
};
with the Visual Studio 2013 C++ compiler I get error:
error C2440: 'initializing' : cannot convert from 'initializer-list' to 'binary_message'. No constructor could take the source type, or constructor overload resolution was ambiguous
With g++ I get:
>g++ main.cpp
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:13:1: error: could not convert '{3, {1, 2, 3}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: could not convert '{2, {1, 2}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: invalid conversion from 'int' to 'unsigned char*' [-fpermissive]
main.cpp:4:2: error: initializing argument 2 of 'binary_message::binary_message(int, unsigned char*)' [-fpermissive]
if I use g++ -std=c++0x main.cpp I still get:
main.cpp:13:1: error: could not convert '{3, {1, 2, 3}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: could not convert '{2, {1, 2}}' from '<brace-enclosed initializer list>' to 'binary_message'
main.cpp:13:1: error: invalid conversion from 'int' to 'unsigned char*' [-fpermissive]
main.cpp:4:2: error: initializing argument 2 of 'binary_message::binary_message(int, unsigned char*)' [-fpermissive]
How do I fix this?
UPDATE
I guess you mean something like this?
#include <vector>
#include <iostream>
struct binary_message
{
binary_message(std::initializer_list<unsigned char> data) : bytes_(data) {}
std::vector<unsigned char> bytes_;
};
int main()
{
binary_message messages[] = {
{ 0x1, 0x2, 0x3 },
{ 0x1, 0x2 },
{ 0x1 }
};
binary_message msg1 = messages[0];
return 0;
}
Upvotes: 1
Views: 661
Reputation: 62573
You need an initializer-list constructor if you want to use initializer lists to construct your object. Your current constructor accepts size of buffer and the buffer, but { 3, { 0x1, 0x2, 0x3 } }
is nothing like that - it is an initializer list of a number and initializer list.
To properly use initializer lists, your class and constructor should be looking approximately following:
binary_message( std::initializer_list<int> data) : data(data) {}
...
std::vector<int> data;
And you would not use size
at all - the size of vector would tell you.
Upvotes: 1