【发布时间】: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