Component of the Week #25: bsls_nameof
- Summary:
A class template that can conveniently stringify a type’s name.
The bsls::NameOf class template converts a class type to a human-readable string that can be used in log messages and exception objects. This class (template) is frequently useful in templated code, where knowing the type used to instantiate the template is particularly informative.
For example:
bsl::cout << bsls::NameOf<int>() << bsl::endl; // int
bsl::cout << bsls::NameOf<double>() << bsl::endl; // double
bsl::cout << bsls::NameOf<bdlt::Date>() << bsl::endl; // bdlt::Date
Note that we’ve created three nameless, temporary objects that are
implicitly convertible to a const char *.
Resulting output is:
int
double
bdlt::Date
In addition to bsls::NameOf, the component provides a free function,
bsls::nameOfType, that can be used to avoid spelling out the type
name if you have an instance of the type available.
For example:
template <class t_TYPE>
int encode(const t_TYPE& value) {
// ...
if (0 != rc) {
bsl::cout << "Error encoding type " << bsls::nameOfType(value)
<< bsl::endl;
return -1;
}
// ...
return 0;
}
If there is an error encoding a bdlt::Date value, we get the message:
Error encoding type bdlt::Date
For more details and examples, see: