c++ - 自动将 std::string 转换为 char* 而无需每次调用​​ c_str() 的最佳方法

标签 c++ stdstring

我经常使用 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/

相关文章:

c++ - std::string::c_str 和 std::string::data 有什么区别?

c++ - 如何使用继承作为参数的 std::string?

c++ - 为什么我的复制构造函数不起作用?

c++ - 使用相同的 key boost 访问许多 std::maps

c++ - 为什么我使用 HeapMemView 找不到分配在堆上的内存?

c++ - 不允许抽象类类型 "Connection"的对象

c++ - 了解在共享库中重载 operator new 的行为

C++ 编译器错误(试图创建 vector 的静态 vector )

c++ - 在 Windows 下使用 C++ 计算处理器

c++ - 如何从 std::string 中取出 2 个字符并将其转换为 C++ 中的 int?