Tuesday Coding Tip 13 — Deleting problematic overloads

●5 ●35 ●98
calendar_today • 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.


Suppose you have a C++ function for opening a file stream that accepts a path to a file and a string (view) with open-mode specifications (like fopen). The issue is, even though your API is strongly typed, users can still swap the arguments by accident and don’t get a compile time error, due to implicit conversions from string-like constants.

Luckily, there is an easy hack with which you can disable implicit conversions for one particular function by explicitly deleting all overloads (via auto template) and allowing just one particular version. The coolest thing is that even the return value doesn’t have to match!

#include <filesystem>

using path = std::filesystem::path;

void fopen2(const auto&, const auto&) = delete;

FILE* fopen2(const path& fp, const std::string& mode)
{
    /* dummy implementation */
    return nullptr;
}

int main()
{
    // error: call to deleted function 'fopen2'
    // note: candidate function [with auto:1 = char[11], auto:2 = char[2]] has been explicitly deleted
    fopen2("myfile.txt", "r");

    // This is ok
    fopen2(path { "myfile.txt" }, std::string { "r" });
    return 0;
}

Want more #programming & #cpp deep dives?

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

Part 13 of 33 in Tuesday Coding Tips

More Posts

Tuesday Coding Tip 33 — Imported CMake targets

Jakub Neruda - Dec 1

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
chevron_left
2.2k Points • 138 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!