Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
Just as the typename keyword helps the compiler when
a type identifier is not expected, there is also a potential difficulty with
tokens that are not identifiers, such as the < and >
characters. Sometimes these represent the less-than or greater-than symbols,
and sometimes they delimit template parameter lists. As an example, we ll once
more use the bitset class:
//: C05:DotTemplate.cpp
// Illustrate the .template construct.
#include <bitset>
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
template<class charT, size_t N>
basic_string<charT> bitsetToString(const
bitset<N>& bs) {
return bs. template to_string<charT,
char_traits<charT>,
allocator<charT>
>();
}
int main() {
bitset<10> bs;
bs.set(1);
bs.set(5);
cout << bs << endl; // 0000100010
string s = bitsetToString<char>(bs);
cout << s << endl; // 0000100010
} ///:~
The bitset class supports conversion to string object
via its to_string member function. To support multiple string classes, to_string
is itself a template, following the pattern established by the basic_string
template discussed in Chapter 3. The declaration of to_string inside of bitset looks like this:
template<class charT, class traits, class
Allocator>
basic_string<charT, traits, Allocator> to_string() const;
Our bitsetToString( ) function template above
requests different types of string representations of a bitset. To get a
wide string, for instance, you change the call to the following:
wstring s = bitsetToString<wchar_t>(bs);
Note that basic_string uses default template arguments, so we don t need to repeat the char_traits and allocator arguments in the return value. Unfortunately, bitset::to_string does not use default
arguments. Using bitsetToString<char>( bs) is more convenient
than typing a fully-qualified call to bs.template to_string<char,
char_traits, allocator<char> >( ) every time.
The return statement in bitsetToString( )
contains the template keyword in an odd place right after the dot
operator applied to the bitset object bs. This is because when
the template is parsed, the < character after the to_string
token would be interpreted as a less-than operation instead of the beginning of
a template argument list. The template keyword used in this context tells
the compiler that what follows is the name of a template, causing the <
character to be interpreted correctly. The same reasoning applies to the ->
and ::operators when applied to templates. As with the typename
keyword, this template disambiguation technique can only be used within
template code.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |