问题描述
假设我有一个对象只有std::string_view
构造函数:
struct OnlyStringViewCtor {
std::string str_;
OnlyStringViewCtor(std::string_view str) : str_(str) {}
};
,有一个函数以const OnlyStringViewCtor&
作为参数:
void f(const OnlyStringViewCtor&) {}
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) {}
};