Constructor.addConstructorScalar

Add a constructor function from scalar.

The function must take a reference to Node to construct from. The node contains a string for scalars, Node[] for sequences and Node.Pair[] for mappings.

Any exception thrown by this function will be caught by D:YAML and its message will be added to a YAMLException that will also tell the user which type failed to construct, and position in the file.

More...
class Constructor
@safe nothrow
void
addConstructorScalar
(
T
)
(
const string tag
,
T function
(
ref Node
)
ctor
)

Parameters

ctor T function
(
ref Node
)

Constructor function.

Detailed Description

The value returned by this function will be stored in the resulting node.

Only one constructor function can be set for one tag.

Structs and classes must implement the opCmp() operator for D:YAML support. The signature of the operator that must be implemented is const int opCmp(ref const MyStruct s) for structs where MyStruct is the struct type, and int opCmp(Object o) for classes. Note that the class opCmp() should not alter the compared values - it is not const for compatibility reasons.

Examples

import std.string;

import dyaml.all;

struct MyStruct
{
    int x, y, z;

    //Any D:YAML type must have a custom opCmp operator.
    //This is used for ordering in mappings.
    const int opCmp(ref const MyStruct s)
    {
        if(x != s.x){return x - s.x;}
        if(y != s.y){return y - s.y;}
        if(z != s.z){return z - s.z;}
        return 0;
    }
}

MyStruct constructMyStructScalar(ref Node node)
{
    //Guaranteed to be string as we construct from scalar.
    //!mystruct x:y:z
    auto parts = node.as!string().split(":");
    // If this throws, the D:YAML will handle it and throw a YAMLException.
    return MyStruct(to!int(parts[0]), to!int(parts[1]), to!int(parts[2]));
}

void main()
{
    auto loader = Loader("file.yaml");
    auto constructor = new Constructor;
    constructor.addConstructorScalar("!mystruct", &constructMyStructScalar);
    loader.constructor = constructor;
    Node node = loader.load();
}

Meta