Add objects.declval

This commit is contained in:
Zahary Karadjov 2020-04-22 15:41:42 +03:00
parent ff755bbf75
commit 9a0cded592
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
2 changed files with 38 additions and 1 deletions

View File

@ -25,6 +25,25 @@ template anonConst*(val: untyped): untyped =
const c = val
c
func declval*(T: type): T {.compileTime.} =
## `declval` denotes an anonymous expression of a particular
## type. It can be used in situations where you want to determine
## the type of an overloaded call in `typeof` expressions.
##
## Example:
## ```
## type T = typeof foo(declval(string), declval(var int))
## ```
##
## Please note that `declval` has two advantages over `default`:
##
## 1. It can return expressions with proper `var` or `lent` types.
##
## 2. It will work for types that lack a valid default value due
## to `not nil` or `requiresInit` requirements.
##
default(ptr T)[]
when not compiles(len((1, 2))):
import typetraits

View File

@ -1,4 +1,5 @@
import unittest,
import
unittest, typetraits,
../stew/objects
when defined(nimHasUsed):
@ -34,3 +35,20 @@ suite "Objects":
f(bar)
test "declval":
proc foo(x: int): string =
discard
proc foo(x: var int): float =
discard
type
T1 = typeof foo(declval(int))
T2 = typeof foo(declval(var int))
T3 = typeof foo(declval(lent int))
check:
T1 is string
T2 is float
T3 is string