【问题标题】: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 [duplicate]为什么 C++ 标准中没有 std::string_view 类型的参数的 std::basic_string 类的构造函数[重复]
【发布时间】:2019-08-22 10:59:06
【问题描述】:

标准类std::basic_string 没有接受std::string_view 类型对象作为其参数的“隐式”构造函数的原因是什么?

我希望这个程序能够编译。

#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 );
}

【问题讨论】:

  • @G.M.可悲的是,您的链接只显示了所有的构造函数。您是指底部的模板构造函数吗? (10 和 11)。他们可能会接受 string_view,而且确实会接受,但前提是您理解“convertable_to”涵盖“is”。
  • 实际上,从字符串视图来看,字符串有一个构造函数:basic_string.h:650。它有一个简短的:“从 string_view 构造字符串”。所以我不认为,这是重复的

标签: c++ string constructor c++17 string-view


【解决方案1】:

原因是因为许多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 最初提出了这个问题,LWG 2946 完成了对模板的所有 string_view 函数的调整。通过这样做,不需要调整旧的字符串接口,因此旧代码在 C++17 下编译时不会中断。

【讨论】:

  • 但是你可以写 std::string s( { {"abc", 1 } } );并且没有歧义。:)
  • @VladfromMoscow 那还能用吗? It doesn't here
  • 这行得通。 #include #include struct A { A( const char *, size_t ) { std::cout
  • @VladfromMoscow 啊,很好。也就是说,必须写std::string s( { {"abc", 1 } } ) 而不是std::string s({"abc", 1}); 会使新来者的语言更难。如果std::string s({"abc", 1}); 不起作用,则违反了最不意外原则。
  • 这个hackery的重点是避免破坏现有代码。是否可以用其他方式重写现有代码并不重要。
猜你喜欢
  • 2022-01-03
  • 1970-01-01
  • 2020-10-12
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
相关资源
最近更新 更多