| Ru-Brd |
13.4 String Literal and Floating-Point Template ArgumentsAmong the restrictions on nontype template arguments, perhaps the most surprising to beginning and advanced template writers alike is the inability to provide a string literal as a template argument. The following example seems intuitive enough:
template <char const* msg>
class Diagnoser {
public:
void print();
};
int main()
{
Diagnoser<"Surprise!">().print();
}
However, there are some potential problems. In standard C++, two instances of
Diagnoser
are the same type if and only if they have the same arguments. In this case the argument is a pointer value ”in other words, an address. However, two identical string literals appearing in different source locations are not required to have the same address. We could thus find
Because of these (and
We should also note an additional technical wrinkle in this issue. Consider the following template declarations, and let's assume that the language has been extended to accept string literals as template arguments in this case:
template <char const* str>
class Bracket {
public:
static char const* address() const;
static char const* bytes() const;
};
template <char const* str>
char const* Bracket<T>::address() const
{
return str;
}
template <char const* str>
char const* Bracket<T>::bytes() const
{
return str;
}
In the previous code, the two member functions are identical except for their
A related issue is the ability to provide floating-point literals (and simple constant floating-point expressions) as template arguments. For example:
template <double Ratio>
class Converter {
public:
static double convert (double val) const {
return val*Ratio;
}
};
typedef Converter<0.0254> InchToMeter;
This too is provided by some C++ implementations and
|
| Ru-Brd |
| Ru-Brd |
13.5
|
| Ru-Brd |