Let's say this the bare bone for a non zero-able type.
template<typename T>
struct NonZero {
T val;
};
My question is if it's possible to make a constructor for NonZero
which to take a literal of type T
and statically check if it's non-zero and then assigns it to val
.
NonZero<int> n( 0 ); // compilation error
NonZero<int> n( 1 ); // ok
Or is there a better way to archieve a non zero type?
Just thought of another approach, which will provide you a constructor which takes a value as an argument.
The core idea is to make the constructor templated and pass the value as a template argument. Unfortunately, it's impossible to do this in a straightforward way, but we can use a workaround from this question:
template<typename T>
struct NonZero {
const T value;
template<T x>
NonZero(std::integral_constant<std::enable_if_t<x != T(0), T>, x>) : value(x) {
}
};
Usage:
auto v = NonZero<int>(std::integral_constant<int, 1>()); // OK
auto v2 = NonZero<int>(std::integral_constant<int, 0>()); // Compilation error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With