Mateen Ulhaq Mateen Ulhaq - 3 months ago 13
C++ Question

Inline char to std::string conversion

Is there a built-in method for constructing a

std::string
based on a given
char
?

The reason I ask this is because I want to make a function call directly within the
if
statement:

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

for(auto rit = s.rbegin(); rit != s.rend(); ++rit)
{
if(func(*rit))
{
//
}
}


I've tried the following:

std::string(*rit)
static_cast<std::string>(*rit)

Answer

The most concise way since C++11 is to construct via an initializer list:

func({*rit})

or if you need to explicitly specify the type (for a function template):

func(std::string{*rit})

For pre-C++11, it is the 2nd overload of the std::string's constructor:

func(std::string(1, *rit))
Comments