Voldemort types

From D Wiki
Revision as of 18:22, 14 December 2012 by Quickfur (talk | contribs) (subverting unnameability)
Jump to: navigation, search

In D, a Voldemort type is a type that cannot be named outside of the scope it's declared in, but code outside the scope can still use this type by taking advantage of D's static type inference.

Usage

For example:

// Note: the return type is auto, because we cannot actually name it outside the function!
auto createVoldemortType()
{
    struct TheUnnameable
    {
        int nameableMember=100;
    }
    return TheUnnameable(123);
}

Here is how the Voldemort type can be used:

auto voldemort = createVoldemortType();
writeln(voldemort.nameableMember);  // prints 123

The type of the variable voldemort cannot be explicitly named here, because that name is only accessible inside the function createVoldemortType. However, we can still declare variables of that type by using D's static type inference.

Purpose

This section is a stub. Please help the wiki by adding more content here.

Voldemort types are widely used in Phobos's range-based functions.

Subverting unnameability

Although we cannot directly name a Voldemort type, there is an indirect way to refer to it using the typeof operator:

// Declares voldemort to be of the same type as the
// return type of the function createVoldemortType.
typeof(createVoldemortType()) voldemort;

writeln(voldemort.nameableMember);  // prints 100

Here, we've successfully created an instance of the Voldemort type without being able to refer to its type name directly. We can even use an alias to make our code more readable:

alias typeof(createVoldemortType()) TheNowNameable;

// Look, ma! We now have an explicit name for the Voldemort type:
TheNowNameable voldemort;
writeln(voldemort);  // prints 100

See also