GAT with generic constants

I would like to use generic associated types with generic constants. How can I get this code to work?

#![allow(incomplete_features)]
#![feature(generic_const_exprs)]

trait Trait {
    type SS<const N: usize>;
}

struct S<const N: usize>;

struct U<const N: usize>;

impl<const C: usize> Trait for U<C> {
    type SS<const N: usize> = S<{C + N}>;
}

The compiler complains that:

   Compiling playground v0.0.1 (/playground)
error: unconstrained generic constant
  --> src/main.rs:13:31
   |
13 |     type SS<const N: usize> = S<{C + N}>;
   |                               ^^^^^^^^^^
   |
   = help: try adding a `where` bound using this expression: `where [(); {C + N}]:`

error: could not compile `playground` due to previous error

Here is the link to the playground.

I don't think there's a way to make this code work as is. Try use crate typenum. You may also be interested in crate generic_array.

Thanks for your reply. I checked the typenum crate and found that there is no way to express a number that follows a certain rule such as a number that is greater than N by two. Is there something I am missing?

a number that is greater than N by two.
For this specific case: IsGreater<N2, Output = B1>

Example:

use std::ops::Sub;

use typenum::Diff;
use typenum::{Integer, IsGreater, B1, P1, P2, P4};

fn print<T, N>()
where
    T: Integer,
    N: Integer,
    T: Sub<N>,
    Diff<T, N>: IsGreater<typenum::P2, Output = B1>,
{
    println!("{} - {} > 2", T::to_i32(), N::to_i32());
}

fn main() {
    print::<P2, P1>(); // fails
    print::<P4, P1>(); // Ok
}
2 Likes

This code does not work either. Something needs to be radically changed...

use std::marker::PhantomData;

use typenum::{Integer, Sum};

trait Trait {
    type SS<T: Integer>;
}

struct S<T> {
    phantom: PhantomData<T>,
}

struct U<T: Integer> {
    phantom: PhantomData<T>
}

impl<C: Integer> Trait for U<C> {
    type SS<T: Integer> = S<Sum<T, C>>;
}

Indeed, I'm out of ideas for now :confused: . Maybe we need something like this? (currently not working)

impl<C: Integer> Trait for U<C> 
where C: for<T: Integer> Add<T>
{
    type SS<T: Integer> = S<Sum<T, C>>;
}

I asked similar questions, and it seems cannot be down for now. "unconstrained generic constant" when enabling feature `#![feature(generic_const_exprs)]` · Issue #104400 · rust-lang/rust · GitHub

Thank you for your information. I felt the same thing about the error message. Hopefully the situation will improve in the near future.