Tuesday Coding Tip 13 — Deleting problematic overloads

2 5 29
calendar_todayschedule1 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;
}
Part 1 of 3 in Tuesday Coding Tips
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

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

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23
chevron_left
847 Points36 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
19Posts
10Comments
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!