I have a const basic string in my class:
class foo {
const basic_string<uint16_t> baz;
};
How do I initialize it?
The main goals I want to achieve are those:
I am using c++11.
How do I initialize it?
Using any of the basic_string
constructors. In your example you have used the default constructor. Here is an example of using the initializer list:
const basic_string<uint16_t> baz {
uint16_t(u't'),
uint16_t(u'e'),
uint16_t(u's'),
uint16_t(u't'),
};
I suspect that it would be much easier for you to use std::u16string
instead:
const std::u16string baz = u"test";
The characters can then later be converted to uint16_t
(from char16_t
) when you need that:
uint16_t c = baz[0];
You can combine UTF-16 literals ( u
prefix) with user-defined suffixes:
std::basic_string<uint16_t> operator "" _u16(char16_t const *begin, std::size_t len)
{
std::basic_string<uint16_t> str;
if (begin != nullptr && len != 0) {
char16_t const *end = begin + len;
str.reserve(len);
std::copy(begin, end, std::back_inserter(str));
}
return str;
}
Now you can initialize your strings like so:
std::basic_string<uint16_t> str{u"testing"_u16};
There is no more overhead with this approach than there is creating a "standard" std::string
from a string literal, as in either approach the string must be copied into a new heap allocation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.