www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Auto return type

The D2 docs say: "Function templates can have their return types deduced based
on the first ReturnStatement  in the function:".
This is a little example, that also shows a closure at work:

import std.stdio: putr = writefln;

auto make_counter()(int start_num) {
    int start = start_num;
    return { return start++; };

void main() {
    auto from_ten = make_counter(10);
    auto from_three = make_counter(3);

    putr(from_ten());   // 10
    putr(from_ten());   // 11
    putr(from_three()); // 3
    putr(from_ten());   // 12
    putr(from_three()); // 4

I think it can be useful for the a future version of D2 if also normal
functions allow such return type inference:

auto make_counter(int start_num) { ...

In the current D2 how you can turn that function template make_counter into an
actual function?

Dec 04 2008