【问题标题】:Pass string literal to the function argument which constructor only takes std::string_view将字符串文字传递给构造函数仅采用 std::string_view 的函数参数
【发布时间】:2021-01-23 03:32:32
【问题描述】:

假设我有一个对象只有std::string_view 构造函数:

struct OnlyStringViewCtor {
  std::string str_;
  OnlyStringViewCtor(std::string_view str) : str_(str) {}
};

还有一个以const OnlyStringViewCtor&为参数的函数:

void f(const OnlyStringViewCtor&) {}

当我直接调用f("hello") 时出现编译器错误:

error: invalid initialization of reference of type 'const OnlyStringViewCtor&' from expression of type 'const char [6]'

有什么好的方法可以让f("hello") 正常工作,而不是声明另一个构造函数,例如OnlyStringViewCtor(const char*)

【问题讨论】:

  • f("hello"sv) 适合你吗?
  • 您可以定义接受 string_view 的 f 的重载。或致电f(MyClass{"test"})... 甚至可能是f({"test"})
  • @Dmitry Kuzminov,为我工作,但我只是好奇那里没有指定sv
  • @Patrick Parker。 f({"test"}) 是个好方法,从来没想过。

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


【解决方案1】:

无法拨打f("hello");。这需要从char const [6]std::string_view 的隐式转换,然后再到OnlyStringViewCtor 的隐式转换,但函数参数只允许进行一次隐式转换。

一个简单的解决方法是使用 string_view 文字调用 f,如下所示:

using namespace std::literals;
f("hello"sv);

【讨论】:

    【解决方案2】:

    正如另一个答案所解释的,编译器不会进行多次隐式转换。

    但是,您可以使用模板来弥补差距:

    struct OnlyStringViewCtor {
      std::string str_;
      template<typename T, std::enable_if_t<std::is_constructible_v<std::string, T>, int> = 0>
      OnlyStringViewCtor(T str) : str_(str) {}
    };
    

    https://godbolt.org/z/1reajv

    【讨论】:

    • 使用模板似乎是不错的选择。而采用OnlyStringViewCtor(std::convertible_to&lt;std::string_view&gt; auto const&amp; string_like)等C++20概念就好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多