将字符串文字传递给函数参数,该函数参数构造函数仅采用std :: string_view

问题描述

假设我有一个对象只有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");。这将需要从char const [6]std::string_view的隐式转换,然后再进行一次到OnlyStringViewCtor的隐式转换,但是函数参数只允许一个隐式转换。

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

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

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

但是,您可以使用模板来缩小差距:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...