ENH: Use a macro to print numeric traits values of objects
Use a macro to print numeric traits values of objects. Avoids boilerplate code.
Printed instances found using the regex:
os << indent << "(.*): " << static_cast<typename NumericTraits<(.*)>::PrintType>(m_(.*)) << std::endl;
and substituted using itkPrintSelfNumericTraitsMacro($3, $2);.
PR Checklist
- [X] No API changes were made (or the changes have been approved)
- [X] No major design changes were made (or the changes have been approved)
BTW, almost always the cast to PrintType is useless, the difference is only for char types (their print type is int) and for long double for Sun Studio 32 bit only (cast to double to avoid bug). Just FYI, there is the C++11 trick to avoid useless casts. But it really just FYI, not a request to implement.
#include <type_traits>
#include <iostream>
template<typename T, typename U, std::enable_if_t<!std::is_same<T, U>::value, int> = 0>
T conditional_static_cast(U value) noexcept
{
std::cout << "cast" << std::endl;
return static_cast<T>(value);
}
template<typename T, typename U, std::enable_if_t<std::is_same<T, U>::value, int> = 0>
T conditional_static_cast(U value) noexcept
{
std::cout << "no cast" << std::endl;
return value;
}
int main(int,char**)
{
unsigned int x{ 1U };
unsigned long y{ 1UL };
unsigned long long z{ 1ULL };
size_t a = conditional_static_cast<size_t, unsigned int>(x);
size_t b = conditional_static_cast<size_t, unsigned long>(y);
size_t c = conditional_static_cast<size_t, unsigned long long>(z);
return 0;
}
Thanks for the comment @issakomi. As one never knows beforehand which *Type aliases may end up adopting such types, and given our extensive use of aliases, I think what you propose will be useful to take into account for the macro in case it can be accommodated into it, and probably another reason to use it in order to save typing.
Some care may be required for complex types in the macro, BTW,
template <typename TComponent>
class NumericTraits<std::complex<TComponent>>
{
public:
using Self = std::complex<TComponent>;
// for backward compatibility
using TheType = Self;
using ValueType = TComponent;
using PrintType = Self;