Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependent types in c++, a non zero type

Tags:

c++

types

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?

like image 321
Sherushe Avatar asked Apr 04 '17 13:04

Sherushe


1 Answers

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
like image 160
alexeykuzmin0 Avatar answered Nov 03 '22 04:11

alexeykuzmin0