为什么在 C++ 标准中缺少 class std::basic_string 的构造函数,其参数类型为 std::string_view
Why is there a constructor of the class std::basic_string with a parameter of the type std::string_view absent in the C++ Standard
标准 class std::basic_string
没有接受 std::string_view
类型对象作为参数的 "implicit" 构造函数的原因是什么?
我希望这个程序能够编译。
#include <iostream>
#include <string>
#include <string_view>
struct A
{
void f( const char *s ) const
{
std::cout << "A::f( " << s << " )\n";
}
};
struct B
{
void f( const std::string &s ) const
{
std::cout << "B::f( " << s << " )\n";
}
};
template <typename... Bases>
struct C : Bases...
{
using Bases::f...;
};
int main()
{
C<A, B>().f( std::string_view( "Hello" ) );
// or
std::string_view s( "Hello" );
C<A,B>().f( s );
}
原因是因为许多 string_view
接受函数与同一函数的 std::string
重载不明确。拿
std::string s({"abc", 1});
例如。这要么通过调用 string_view
接受构造函数从 std::string_view
创建一个 std::string
,要么通过
创建一个 std::string
basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator());
LWG 2758 brought this issue up originally and LWG 2946 调整完所有string_view
函数模板。通过这样做 none 需要调整旧的字符串接口,以便在 C++17 下编译时旧代码不会中断。
标准 class std::basic_string
没有接受 std::string_view
类型对象作为参数的 "implicit" 构造函数的原因是什么?
我希望这个程序能够编译。
#include <iostream>
#include <string>
#include <string_view>
struct A
{
void f( const char *s ) const
{
std::cout << "A::f( " << s << " )\n";
}
};
struct B
{
void f( const std::string &s ) const
{
std::cout << "B::f( " << s << " )\n";
}
};
template <typename... Bases>
struct C : Bases...
{
using Bases::f...;
};
int main()
{
C<A, B>().f( std::string_view( "Hello" ) );
// or
std::string_view s( "Hello" );
C<A,B>().f( s );
}
原因是因为许多 string_view
接受函数与同一函数的 std::string
重载不明确。拿
std::string s({"abc", 1});
例如。这要么通过调用 string_view
接受构造函数从 std::string_view
创建一个 std::string
,要么通过
std::string
basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator());
LWG 2758 brought this issue up originally and LWG 2946 调整完所有string_view
函数模板。通过这样做 none 需要调整旧的字符串接口,以便在 C++17 下编译时旧代码不会中断。