C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Extension methods take 2

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 2 Jun 2023 11:10:05 -0400
On Thu, Jun 1, 2023 at 10:45 AM Михаил Найденов via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hello, with explicit object parameter we can have mixins as such:
>
> struct StringUtils {
> template<class T>
> void contains(this T self, char) { ... }
> };
>
> class MyString : public StringUtils {
> ...
> }
>
> We can also have half-baked extensions as such:
>
> struct StringUtils {
> void contains(this class MyString& self, char);
> };
>
> class MyString : public StringUtils {
> ...
> }
>
> void StringUtils::contains(this MyString& self, char) { ... }
>
> This is almost usable. The fact that we need to subclass kills any perceived advantage as the extension becomes part of the implementation, making it no longer an extension.
> One is still better off writing a class-static function to get the extra functionality.
>
> This can be improved by allowing to call StringUtils methods, which have the correct type of the `this` param or it is a template, without subclassing from it!
>
> class MyString {
> ...
> }
>
> struct StringUtils {
> void contains(this MyString& self, char) { ... }
> };
>
> int main() {
> MyString s = "hello";
>
> s.::StringUtils::contains('e');
>
> return 0;
> }
>
> I am using the fully qualified access to show, there is at least one syntax that is perfectly safe. It might not be very practical, but it is a start.

I see no reason to prefer `s.::StringUtils::contains('e');` when
`StringUtils::contains(s, 'e')` does the exact same thing. Why is it
important to declare `contains` as an explicit object parameter
function instead of a static member? Why is putting `s` first,
followed by gruesome syntax, preferable? What's the advantage?

Received on 2023-06-02 15:10:17