I have a simple program that uses a variable template of type std::initializer_list
that stores pairs that contain a type and a text:
using name_t = const char *;
template <typename key_t>
using key_name_t = std::pair<key_t, name_t>;
template <typename type_t>
std::initializer_list<key_name_t<type_t>> values;
The template variable is initialized by a variádica template:
template <typename type_t, typename ... KV>
void init(type_t value, const char *name, KV ... kv)
{
values<type_t> = {{value, name}};
}
When using it:
int main()
{
init(1, "uno", 2, "dos", 3, "tres");
// ~~~~~~~~~~~~~~~~~~~ <--- parámetros ignorados
for (const auto &kv : values<int>)
std::cout << kv.first << '\t' << kv.second << '\n';
return 0;
}
I expected an exit like:
1 uno
But the output is random memory:
-809605168
I thought maybe the pointer within key_name_t
is getting lost so I changed name_t
:
using name_t = const char *const &;
Use constant reference to take advantage of the extension of the life cycle when associated with a constant reference, but then the code causes a segmentation fault
, so I decide to change again name_t
to alias of std::string
and return to receive segmentation fault
.
The complete code:
#include <iostream>
using name_t =
//const char *;
//const char *const &;
std::string;
template <typename key_t>
using key_name_t = std::pair<key_t, name_t>;
template <typename type_t>
std::initializer_list<key_name_t<type_t>> values;
template <typename type_t, typename ... KV>
void init(type_t value, const char *name, KV ... kv)
{
values<type_t> = {{value, name}};
}
int main()
{
init(1, "uno", 2, "dos", 3, "tres");
for (const auto &kv : values<int>)
std::cout << kv.first << '\t' << kv.second << '\n';
return 0;
}
Available at Wandbox 三 へ (へ ਊ) へ ハ ッ ハ ッ .
- Why am I receiving those
segmentation fault
? - Why does the version with
name_t = const char *
point to invalid memory? - How can I get it working properly?