I have an initializer_list of char and want to typecast it to an initializer_list of unsigned char:
// This code doesn't work, and it's used just as an example
reinterpret_cast<initializer_list<unsigned char>>(initializer_list<char>);
How would I do this?
Edit:
Here's what I'm trying to do:
As I'm new to C++, I've been trying to create random programs to learn it. My current goal is to have a class that inherits from basic_string to implement ISO 8859-1. But one of the constructors from basic_string is defined as
basic_string(initializer_list<charT> il, const allocator_type& alloc = allocator_type())
Thus, to implement the following functionality (that I currently see no use, I'm just trying to implement everything from the class)
// ISO_8859_1_String is a basic_string<unsigned char, ..., ...>
// where "..." are the other parameters, which are omitted to improve readability
ISO_8859_1_String testString{'a', 'b', 'c'};
I have to create a constructor that receives an initializer_list of characters and translates it to the character type of ISO_8859_1_String, which is unsigned char. There's where this question enters.
ISO_8859_1_String(initializer_list<char> il,
const allocator_type& alloc = allocator_type()):
basic_string<unsigned char, ..., ...>
(magicFunctionToConvertCharILToUnCharIL(il), alloc){}
Is there a way I can do this, maybe using an auxiliary function to convert the initializer_list to something else, and then to the desired initializer_list?
Solution:
As pointed out by @Brian, I could use the iterators from initializer_list to call the following constructor of basic_string:
template <class InputIterator>
basic_string (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
So I modified my constructor to:
ISO_8859_1_String(initializer_list<char> il,
const allocator_type& alloc = allocator_type()):
basic_string<unsigned char, ..., ...>
(std::begin(il), std::end(il), alloc){}
No, the conversion you are trying to perform cannot be accomplished with a cast---at least, not safely. In addition, there are only three ways to create a new std::initializer_list
object:
std::initializer_list<unsigned char> IL;
std::set<int> {1, 2, 3};
std::initializer_list<int> IL; IL = {1, 2, 3};
Pretty much the only reason initializer lists exist is for convenience when initializing. An initializer list is useless on its own. It sure isn't a great container. If you want to use an initializer_list<char>
to initialize a container of unsigned char
, use the usual range constructor.
std::initializer_list<char> IL {'a', 'b', 'c'};
std::vector<unsigned char> V(IL.begin(), IL.end());