2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Nim] enum にエイリアスを付ける。または class method を実現する。

Last updated at Posted at 2021-08-12

まとめ

typedesc[SomeObject]を第一引数にとろう。型に対して関数が定義できる。

enumにエイリアス

enumDef.nim
type SomeEnum {.pure.} = enum
  ValA
  ValB
  ValC
type OtherEnum {.pure.} = enum
  ValA
  ValB
  ValC

template AliasA(someEnum: typedesc[SomeEnum]): SomeEnum =
  SomeEnum.ValA

assert SomeEnum.ValA == SomeEnum.AliasA
# error!
# assert SomeEnum.ValA == AliasA
# assert SomeEnum.ValA == OtherEnum.AliasA
# echo OtherEnum.AliasA
# echo AliasA

template defineAlias*(TEnum: typedesc; value, alias: untyped): untyped =
  template alias*(tEnum: typedesc[TEnum]): TEnum =
    TEnum.value

SomeEnum.defineAlias(ValB, AliasB)

assert SomeEnum.ValB == SomeEnum.AliasB

class method

type Object = object
  value: int
var `Object.staticmember`: int = 10

proc init(TObject: typedesc[Object]; value: int): Object =
  Object(value: value)
template staticmember(_: typedesc[Object]): int = `Object.staticmember`

echo repr Object.init(10)
# stdout: 10

echo Object.staticmember
# stdout: 10
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?