简体   繁体   English

如果调用 function 的特定重载,如何引发编译时错误?

[英]How to provoke a compile-time error if a specific overload of a function is called?

According to https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view , std::basic_string_view class has 7 overloaded ctors.根据https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_viewstd::basic_string_view class 有 7 个重载 ctor。 I only care about 2 of them since right now I don't use the rest of them in my code.我只关心其中的 2 个,因为现在我不在我的代码中使用它们的 rest。

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?这样做的正确方法是什么?

Add another overload taking const char* and mark it as delete (since C++11).添加另一个采用const char*的重载并将其标记为删除(C++11 起)。

void func( const char* str ) = delete;

LIVE居住

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果可以使用一组特定参数调用的函数存在,如何在编译时检查? - How to check at compile-time if a function that can be called with a specific set of arguments exists? 如何向特定功能添加编译时元数据/行为 - how to add compile-time metadata/behavior to specific function 调用 constexpr 函数的给定重载时触发编译时错误 - Trigger compile time error when given overload of the constexpr function is called 如果某些成员函数尚未被调用,是否可能产生编译时错误 - Is it possible to generate a compile-time error if some member function hasn't been called 逻辑运算符在称为的函数上导致编译时错误 - Logical operator causing compile-time error on functions called 如何检查在编译时是否调用了模板化方法? - How can I check if a templated method was called at compile-time? 如何为编译时已知的参数的多个值编译函数 - How to compile a function for multiple values of a parameter known in compile-time 专门使用模板函数来生成编译时错误 - Specialize a Template Function to Generate a Compile-Time Error 在 c++ function 中计算斐波那契并抛出编译时错误 - Computing fibonacci in c++ function and throwing compile-time error 如何计算在编译时调用的特定函数的数量 - how to count number of a specific function be called at compile time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM