hrektts
November 17, 2022, 2:50am
1
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 .
hrektts
November 17, 2022, 6:05am
3
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
hrektts
November 17, 2022, 9:45am
5
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 . 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>>;
}
hrektts
November 18, 2022, 1:03am
8
Thank you for your information. I felt the same thing about the error message. Hopefully the situation will improve in the near future.
system
Closed
February 16, 2023, 1:03am
9
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.