我经常使用 std::string
,但我使用的各种库都将 const char*
作为参数。我很困惑 std::string
没有到 const char*
的转换运算符。所以我正在寻找一些方法来不必在我的项目中一直调用 c_str()
。
有办法吗?
最佳答案
给定以下 API 接口(interface):
namespace someapi {
void foo(const char* pstr);
}
我们可以这样做:
namespace wrap_someapi
{
inline decltype(auto) foo(const char* pstr)
{
return someapi::foo(pstr);
}
inline decltype(auto) foo(std::string const& s)
{
return foo(s.c_str());
}
// or, in c++17
inline decltype(auto) foo(std::string_view s)
{
return foo(s.c_str());
}
}
现在在客户端代码中,而不是调用:
someapi::foo(s.c_str());
我们称:
wrap_someapi::foo(s);
因此,我们在提高安全性和优雅性的同时减少了冗长。
关于c++ - 自动将 std::string 转换为 char* 而无需每次调用 c_str() 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44572719/