• Advertisement
Sign in to follow this  

D language code question

This topic is 999 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

protected string delegate() getTimePeriod()
{
immutable string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

string path     = buildPath(this._config.path.officialDirectory, "test");

return delegate()
{
	auto time = Clock.currTime();
	return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);
};
}

My problem here, is the return type. Its a delegate. However, at the end of the function, I don't really understand what the delegate that is returned, points to.

 

I mean, format returns just a string, not an actual function. So the delegate points to...a string?

Share this post


Link to post
Share on other sites
Advertisement

I'm not super familiar with D, but from similar languages I'm guessing that "getTimePeriod" returns a function (delegate) that returns a string, defined as follows:


auto time = Clock.currTime();
return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);

So if you were to write "getTimePeriod()()", you would get a string.

Edited by Salty Boyscouts

Share this post


Link to post
Share on other sites
return delegate()

{

auto time = Clock.currTime();

return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);

};

 

The quoted section returns an anonymous function (which itself will return a string when called).

Share this post


Link to post
Share on other sites

You can think of a delegate as something like this:

struct Delegate {
    void* context;
    void* funcPtr;
}

So when you return a delegate, you're returning an instance of a type similar to this struct. The context is what allows the delegate to access any variables that were in scope at the point the delegate was created. It's what distinguishes a delegate from a function pointer, which has no context.

Edited by Aldacron

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement