c++

What differs std::to_string() from static_cast<std::string>()?


While on LearnCpp.com, I stumbled across a function called std::to_string(), but the tutorial didn't really elaborate on what it exactly did different than static_cast<std::string>(), so now I'm confused.

Also, std::string is a type, right?

I attempted to use them and got a compiler error, so I want to know in which scenario should I use std::to_string() or static_cast<std::string>().

'static_cast': cannot convert from 'char' to 'std::string'
#include <iostream>
#include <string>

int main()
{
    char x{ 'a' };

    std::cout << std::to_string(x) << "\n";
    std::cout << static_cast<std::string>(x) << "\n";
    return 0;
}

Solution

  • std::to_string is a function from the standard library. It has many overloads for different argument types that all return a std::string. I recommend to be careful with using it with a char. It might not do what you expect.

    static_cast on the other hand is not a function, it's a language feature. It attempts a static cast conversion. There is no conversion from char to std::string, hence static_cast<std::string>(x) is an error.

    There is no reason to expect the two to do the same thing.