【问题标题】:Conditional type in Nim. How to get half unsigned int type from a int function parameter?Conditional type in Nim. How to get half unsigned int type from a int function parameter?
【发布时间】:2022-07-31 06:10:30
【问题描述】:

See bellow sample code. Please help. Thanks! Blow is non working Nim version sample code.

macro GetHalfUInt(anyInt : untyped ): untyped =
  when sizeof(anyInt) == 8:
    uint32
  else when sizeof(anyInt) == 4:
    uint16
  else when sizeof(anyInt) == 2:
    uint8


proc getHighBitsAsHalfUInt[AnyInt](x: AnyInt) : GetHalfUInt(AnyInt) =
  result = (x shr (sizeof(AnyInt) * 4)).GetHalfUInt(AnyInt)

Below is working C++ code.

template<class AnyInt>
struct GetHalfUInt {
    static_assert( std::is_integral_v<AnyInt>, "Must be Int type!");
    using type = std::conditional_t<sizeof(AnyInt) == 8, uint32_t, 
                    std::conditional_t<sizeof(AnyInt) == 4, uint16_t, uint8_t> >;
};

template<class AnyInt>
auto getHighBitsAsHalfUInt(AnyInt x) {
    using Res = typename GetHalfUInt<AnyInt>::type;
    return Res(x >> (sizeof(AnyInt)*4));
}

【问题讨论】:

    标签: nim-lang


    【解决方案1】:

    There are a few issues here. Macros are not equivalent to C++ templates, macros in Nim are VM operations on AST that can emit a new AST, they're not just code substitution. Secondly Nim's elif branch is used for when branches. Finally here is a working implementation:

    template getHalfUInt(anyInt: typedesc[SomeInteger]): untyped =
      when sizeof(anyInt) == 8:
        uint32
      elif sizeof(anyInt) == 4:
        uint16
      elif sizeof(anyInt) == 2:
        uint8
      else:
        # perhaps #{.error: "Cannot get a half integer of a 8 bit int".}
        anyInt
        
    proc getHighBitsAsHalfUInt[T: SomeInteger](x: T): auto =
      getHalfUInt(T)(x shr (sizeof(x) * 4))
      
    var 
      a = 0xffffff
      aHalf = a.getHighBitsAsHalfUint()
      b = 0xffffi16
      bHalf = b.getHighBitsAsHalfUint()
      c = 0xffffi32
      cHalf = c.getHighBitsAsHalfUint()
    echo typeof(aHalf), " ", aHalf
    echo typeof(bHalf), " ", bHalf
    echo typeof(cHalf), " ", cHalf
    

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-27
      • 2022-12-28
      • 2022-08-27
      • 2022-11-09
      • 2022-12-02
      • 1970-01-01
      相关资源
      最近更新 更多