Home > Back-end >  How to provoke a compile-time error if a specific overload of a function is called?
How to provoke a compile-time error if a specific overload of a function is called?

Time:12-04

According to https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view, std::basic_string_view class has 7 overloaded ctors. I only care about 2 of them since right now I don't use the rest of them in my code.

These are the instances that I care about:

constexpr basic_string_view( const CharT* s, size_type count );
constexpr basic_string_view( const CharT* s );

I need to prevent the code from calling the second one (due to it potentially causing a buffer overflow for non-null terminated buffers).

I have something like below:

#include <iostream>
#include <sstream>
#include <string>
#include <array>

void func( const std::string_view str )
{
    if ( str.empty( ) )
    {
        return;
    }

    std::stringstream ss;

    if ( str.back( ) == '\0' )
    {
        ss << str.data( );
    }
    else
    {
        ss << std::string{ str };
    }
}

int main()
{
    std::array<char, 20> buffer { };
    std::cin.getline( buffer.data( ), 20 );

    const std::string_view sv { buffer.data( ), buffer.size( ) };

    func( sv ); // should be allowed
    func( { buffer.data( ), buffer.size( ) } ); // should be allowed
    func( buffer.data( ) ); // should NOT be allowed!
}

What is the correct way of doing this?

CodePudding user response:

Add another overload taking const char* and mark it as delete (since C 11).

void func( const char* str ) = delete;

LIVE

  • Related