内联char到std :: string的转换

Mat*_*haq 1 c++ string type-conversion c++11

是否有内置的方法来构建std::string基于给定的char

我问这个的原因是因为我想在if语句中直接进行函数调用:

// Given function prototype
bool func(std::string s);

for(auto rit = s.rbegin(); rit != s.rend(); ++rit)
{
    if(func(*rit))
    {
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

std::string(*rit)
static_cast<std::string>(*rit)
Run Code Online (Sandbox Code Playgroud)

Log*_*uff 5

自C++ 11以来最简洁的方法是通过初始化列表构建:

func({*rit})
Run Code Online (Sandbox Code Playgroud)

或者如果需要显式指定类型(对于函数模板):

func(std::string{*rit})
Run Code Online (Sandbox Code Playgroud)

对于pre-C++ 11,它是std::string构造函数的第二个重载:

func(std::string(1, *rit))
Run Code Online (Sandbox Code Playgroud)

  • 在C++ 11中,您可以编写`func({rit,rit + 1});`等. (2认同)