Your code is decidedly a "C" style approach, in C++20 I would do this :
#include <array>
#include <string_view>
#include <concepts>
struct audio_file_t
{
int id;
std::string_view name;
};
int main()
{
constexpr auto files = std::to_array<audio_file_t>({{ 1, "file1" }, { 2, "file2" }});
static_assert(files.size() == 2);
}
Update to include a more nested structure (no longer constexpr)
#include <array>
#include <vector>
#include <string_view>
#include <iostream>
#include <format>
struct audio_file_t
{
int id;
std::string_view name;
};
struct message_files_t
{
int id;
std::vector<audio_file_t> files;
};
std::ostream& operator<<(std::ostream& os, const audio_file_t& file)
{
std::cout << std::format("File id : {}, name : {}", file.id, file.name);
return os;
}
int main()
{
constexpr auto files = std::to_array<audio_file_t>({{ 1, "file1" }, { 2, "file2" }});
static_assert(files.size() == 2);
std::vector<audio_file_t> temp{{ 4, "file3.1" }, { 5, "file3.1" }, { 6, "file3.1" }};
// This is the initialization you're looking for
std::vector<message_files_t> multi_files{
{11, {{ 1, "file1.1" }, { 2, "file2.1" }}},
{22, {{ 3, "file2" }}},
{33, {{ 4, "file3.1" }, { 5, "file3.2" }, { 6, "file3.3" }}}
};
for(const auto& message_files : multi_files)
{
std::cout << "Message Files, id = " << message_files.id << "\n";
for( const auto& audio_file : message_files.files)
{
std::cout << audio_file << "\n";
}
}
}
{{1,500}, {2,500}}is not an array literal. What are you trying to do here? Assuming the error in question is fixed, macro expansion would lead tomessage_files files[1] = { {sizeof((audio_file []) {{1,500}, {2,500}}) / sizeof(audio_file), {{1,500}, {2,500}}} };which doesn't make sense syntactically.message_files. This is a class with flexible array member (which btw. are not valid in standard C++), so it should be individually allocated for.(audio_file []) arris also not valid C++ syntax. Compound literals exist in C, but not C++.