[英]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_view , std::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?这样做的正确方法是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.