Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I initialize a std::array<uint8_t with a string literal?

I write a lot of C code interacting with instruments using UART serial ports. I’m starting a new project where I’m trying to use a more object oriented approach with C++. Here’s how I’ve defined and sent commands in the past using C.

uint8_t  pubx04Cmd[] = "$PUBX,04*37\r\n";
HAL_UART_Transmit(&hUART1, pubx04Cmd, sizeof(pubx04Cmd), 5000); 

Which is pretty darn simple. C++ std::arrays have the size built in which seems kind of useful. But here’s the only way I’ve figured out how to do it.

const char pubx04CString[] = "$PUBX,04*37\r\n";
std::array<uint8_t, 14> pubx04CPPArray;
std::copy(std::begin(pubx04CString), std::end(pubx04CString), pubx04CPPArray.begin());
HAL_UART_Transmit(&hUART1, pubx04CPPArray.data(), pubx04CPPArray.size(), 5000);

Which seems pretty clunky compared to the C way to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Is there a cleaner way to do this using std::array?

  • Is there any real benefit to using std::arrays vs C arrays for this situation?

>Solution :

std::array is an aggregate, i.e. a possible implementation may be like

template <typename T, size_t S>
struct array {
  T a[S];
  // ...
};

The enclosed array can be initializes as usual:

std::array<uint8_t, 14> pubx04Cmd{"$PUBX,04*37\r\n"};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading