Tuesday Coding Tip 31 — Deducing this

●5 ●28 ●93
calendar_today ago • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Have you ever found yourself writing a custom C++ container, with every access method having regular, const, and possibly move versions? So much code duplication!

template<class T, std::size_t Size>
class Vec {
public:
    // note that I have to ref-qualify the function
    // only because I have r-value ref functions
    T& operator[](std::size_t index) & {
        return data[index];
    }

    const T& operator[](std::size_t index) const& {
        return data[index];
    }

    T&& operator[](std::size_t index) && {
        return data[index];
    }
    
    T&& operator[](std::size_t index) const&& {
        return data[index];
    }

private:
    T data[Size];
};

C++23 comes with a new feature that helps reduce this boilerplate by explicitly putting this pointer into the function declaration and deducing the constness and possible r-valueness from it.

template<class T, std::size_t Size>
class Vec {
public:
    // Return type is dependent on qualifiers on self, must be auto
    auto&& operator[](this auto&& self, std::size_t index) {
        // data must be accessed via 'self'
        // implicit or 'this' wouldn't work
        return self.data[index];
    }

private:
    T data[Size];
};

The parameter has to be templated (or auto) for it to be a universal reference. You are also forced to access member functions and attributes via that parameter, instead of this pointer.

A slight disadvantage is that the function’s return type cannot be explicitly stated but rather left to be auto, making the API harder to read without an Intellisense.

Want more #cpp & #cpp deep dives?

Join 6,001+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 31 of 31 in Tuesday Coding Tips

2 Comments

0 votes
0

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21
chevron_left
2.1k Points • 126 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
43Posts
37Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!