How to implement conditional branch in constant generics

When I try to compile the following code, I always encounter the trait bound `Condition<Left, Right, { Left::TYPE_SIZE > Right::TYPE_SIZE }>: IDataType` is not satisfied

use std::marker::PhantomData;

trait IDataType {
    const TYPE_SIZE: usize;
    type DataType: IDataType;
}

struct Condition<Left: IDataType, Right: IDataType, const condition: bool> {
    left: PhantomData<Left>,
    right: PhantomData<Right>,
}

impl<Left: IDataType, Right: IDataType> IDataType for Condition<Left, Right, true> {
    const TYPE_SIZE: usize = Left::TYPE_SIZE;
    type DataType = Left::DataType;
}

impl<Left: IDataType, Right: IDataType> IDataType for Condition<Left, Right, false> {
    const TYPE_SIZE: usize = Right::TYPE_SIZE;
    type DataType = Right::DataType;
}

struct MaxSizeType<Left: IDataType, Right: IDataType> {
    left: PhantomData<Left>,
    right: PhantomData<Right>,
}

impl<Left: IDataType, Right: IDataType> IDataType for MaxSizeType<Left, Right> {
    const TYPE_SIZE: usize = 0;

    type DataType = <Condition<Left, Right, { Left::TYPE_SIZE > Right::TYPE_SIZE }> as IDataType>::DataType;
}

See:

In it you can see you need to forward the bounds on the const bool, such as:

  impl<Left: IDataType, Right: IDataType> IDataType for MaxSizeType<Left, Right>
+ where
+     Condition<Left, Right, { Left::TYPE_SIZE > Right::TYPE_SIZE }> : IDataType,
  {
      const TYPE_SIZE: usize = 0;

      type DataType = <Condition<Left, Right, { Left::TYPE_SIZE > Right::TYPE_SIZE }> as IDataType>::DataType;
  }
3 Likes

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.