Get return type statically
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 27 19:08:01 PDT 2016
On 06/27/2016 06:41 PM, Smoke Adams wrote:
> I have a type
>
> public class SuperFunction(T)
> {
> T t;
> return(T) Do() { return t(); }
> }
>
> where T is a delegate or function. First, I would like to be able to
> specify that this must be the case for SuperFunction so we can't pass
> non-function/delegates for T. Second, How to specify the return type of
> Do to match that of T.
>
> e.g., SuperFunction!(bool function())
>
> then return(T) should be bool.
The simplest thing is to define the return type as 'auto'.
>
> Similarly, I would like to extra the T's parameters and make Do have
> them also.
>
> This way, SuperFunction!T.Do emulates T in every way.
>
>
std.traits is your friend. :)
import std.traits;
public class SuperFunction(alias func)
if (isCallable!func) {
auto Do(Parameters!func args) { return func(args); }
}
void main() {
auto sf = new SuperFunction!((int i) => i * 2);
assert(sf.Do(42) == 84);
}
Ali
More information about the Digitalmars-d-learn
mailing list