Game Development Reference
In-Depth Information
The other important aspect of the lines in Listing 13-1 is the fact that they create type aliases. You've
been using the
string
alias already in this topic. What the alias has done is allow you to use the
string
keyword when declaring
string
variables rather than having to type the full typename, which
would be
basic_string<char>
.
The concepts of template specialization and type aliases are all you need to understand about
templates to be able to use the functionality provided by the STL.
Note
Type aliases are a modern feature of C++11. If your compiler does not support type aliases, you can
use an older style. The code
typedef basic_string<char> string;
would serve a similar purpose.
Constructing Strings
The
basic_string
template provides many different types of constructors for creating instances of
strings. Listing 13-2 shows how to create empty strings.
Listing 13-2. An Empty
String
string emptyString;
Listing 13-3 shows how you can create strings from a C-style string literal.
Listing 13-3. A Literal
String
string literalString{ "This is a literal string!" };
You can also use a copy constructor to copy a string as shown in Listing 13-4.
Listing 13-4. Copying a
String
string copiedString{ literalString };
This example has copied the
literalString
from Listing 13-3 into
copiedString
. This means that
both
literalString
and
copiedString
contain the literal
"This is a literal string!"
. They are
both still discrete copies, so any changes you make to one do not affect the other.
It's also possible to initialize new strings from substrings; that is, to specify the specific start
position and optionally the number of characters you wish to copy. Listing 13-5 shows the possible
substring initializers.
Listing 13-5. Initializing Strings with Substrings
string listerStartPosition{ "This is a literal string!", 5 };
string listerStartPositionAndNumber{ "This is a literal string!", 5, 4 };
This example will result in
literalStartPosition
containing
"is a literal string!"
and
literalStartPositionAndNumber
will contain
"is a"
. This is because the start position 5 is passed into
both and in the second line we also specify that we would only like to copy the next four characters.