Skip to content

Instantly share code, notes, and snippets.

@gmpreussner
Last active March 1, 2016 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmpreussner/6424afb5d8dd181cde4e to your computer and use it in GitHub Desktop.
Save gmpreussner/6424afb5d8dd181cde4e to your computer and use it in GitHub Desktop.
type
Foo[T] = concept x
x.foo(T)
proc foobar[T](f: Foo[T]) =
f.foo(42)
type
FooImpl[T, U] = object
a: T
b: U
proc foo[T, U](f: FooImpl[T, U], t: T) =
echo $t
when isMainModule:
var f: FooImpl[int, float]
echo f is Foo[int] # true
f.foo(42) # 42
f.foobar # Error: type mismatch: got (FooImpl[system.int, system.float])
# but expected one of:
# foo.foobar(f: Foo[foobar.T])
@gmpreussner
Copy link
Author

U is not essential for this to fail:

type
  Foo[T] = concept x
    x.foo(T)

proc foobar[T](f: Foo[T]) =
  f.foo(42)


type
  FooImpl[T] = object
    a: T

proc foo[T](f: FooImpl[T], t: T) =
  echo $t


when isMainModule:
  var f: FooImpl[int]

  echo f is Foo[int]  # true

  f.foo(42)           # 42

  f.foobar            # Error: type mismatch: got (FooImpl[system.int)
                      # but expected one of: 
                      #   foo.foobar(f: Foo[foobar.T])

@gmpreussner
Copy link
Author

even T is not needed in the impl type:

type
  Foo[T] = concept x
    x.foo(T)

proc foobar[T](f: Foo[T]) =
  f.foo(42)


type
  FooImpl = object

proc foo(f: FooImpl, t: int) =
  echo $t


when isMainModule:
  var f: FooImpl

  echo f is Foo[int]  # true

  f.foo(42)           # 42

  f.foobar            # Error: type mismatch: got (FooImpl)
                      # but expected one of: 
                      #   foo.foobar(f: Foo[foobar.T])

@gmpreussner
Copy link
Author

Workaround:

type
  Foo[T] = concept x
    type Z = x.T                     # <---
    x.foo(Z)

proc foobar(f: Foo) =            # <---
  f.foo(42)


type
  FooImpl[T, U] = object
    a: T
    b: U

proc foo[T, U](f: FooImpl[T, U], t: T) =
  echo $t


when isMainModule:
  var f: FooImpl[int, float]

  echo f is Foo[int]  # true

  f.foo(42)           # 42

  f.foobar            # 42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment