You can run this code
#include <type_traits>
int main()
{
std::integral_constant<int, 3> a;
std::integral_constant<int, 2> b;
auto c = a + b;
static_assert(std::is_same<decltype(c), int>::value);
}
to verify that c
type is int
.
As the compiler has all the required information, on my side I prefer to get a std::integral_constant<int, 5>
type, this guarantee compile-time computations and reduced size storage. That's the reason why, I often use stuff like:
#include <type_traits>
template <typename T, T A, T B>
std::integral_constant<T, A + B> operator+(
const std::integral_constant<T, A>& a,
const std::integral_constant<T, B>& b) noexcept
{
return decltype(a + b)();
}
int main()
{
std::integral_constant<int, 3> a;
std::integral_constant<int, 2> b;
auto c = a + b;
static_assert(std::is_same<decltype(c), std::integral_constant<int, 5>>::value);
}
in my code.
I have two questions:
- Were there any discussions to define such operator overloading in the C++ std lib?
- Are there any risks in defining such overloads in our code (interference with the standard library, side effect)?
Aucun commentaire:
Enregistrer un commentaire