Horizon Posted December 27, 2024 Share Posted December 27, 2024 In 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); }; View the full article Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.