In C++, How Can I Make a Default Parameter be the This Pointer of the Caller? -- Raymond Chen

RaymondChen_5in-150x150.jpgIn C++, associating member objects like properties or events with their containing class often requires passing this redundantly. This article explores a generalized, flexible solution using templates, variadic arguments, and deducing this to streamline ownership initialization without boilerplate.

In C++, How Can I Make a Default Parameter be the This Pointer of the Caller? Revisited

by Raymond Chen

From the article:

Some time ago, we looked at making the default parameter of a method be the this pointer of the caller. The scenario was something like this:

struct Property
{
    Property(char const* name, int initial, Object* owner) :
        m_name(name), m_value(initial), m_owner(owner) {}

    ⟦ other methods elided - use your imagination ⟧

    char const* m_name;
    Object* m_owner;
    int m_value;
};

struct Widget : Object
{
    Property Height{ "Height", 10, this };
    Property Width{ "Width", 10, this };
};

and we didn’t want to have to type this as the last parameter to all the Property constructors. We came up with this:

template<typename D>
struct PropertyHelper
{
    Property Prop(char const* name, int initial)
    { return Property(name, initial, static_cast<D*>(this)); }
};

struct Widget : Object, PropertyHelper<Widget>
{
    Property Height = Prop("Height", 10);
    Property Width = Prop("Width", 10);
};

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.