mirror of
https://github.com/status-im/nim-stew.git
synced 2025-02-23 09:18:16 +00:00
Add objects.declval
This commit is contained in:
parent
ff755bbf75
commit
9a0cded592
@ -25,6 +25,25 @@ template anonConst*(val: untyped): untyped =
|
|||||||
const c = val
|
const c = val
|
||||||
c
|
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))):
|
when not compiles(len((1, 2))):
|
||||||
import typetraits
|
import typetraits
|
||||||
|
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import unittest,
|
import
|
||||||
|
unittest, typetraits,
|
||||||
../stew/objects
|
../stew/objects
|
||||||
|
|
||||||
when defined(nimHasUsed):
|
when defined(nimHasUsed):
|
||||||
@ -34,3 +35,20 @@ suite "Objects":
|
|||||||
|
|
||||||
f(bar)
|
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
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user