How to construct a std::string with embedded values, i.e. "string interpolation"?

C++String Interpolation

C++ Problem Overview


I want to create a string with embedded information. One way (not the only way) of achieving what I want is called string interpolation or variable substitution, wherein placeholders in a string are replaced with actual values.

In C, I would do something like this:

printf("error! value was %d but I expected %d",actualValue,expectedValue)

whereas if I were programming in python, I would do something like this:

"error! value was {0} but I expected {1}".format(actualValue,expectedValue)

both of these are examples of string interpolation.

How can I do this in C++?

Important Caveats:

  1. I know that I can use std::cout if I want to print such a message to standard output (not string interpolation, but prints out the kind of string I want):

cout << "error! value was " << actualValue << " but I expected "
<< expectedValue;

I don't want to print a string to stdout. I want to pass a std::string as an argument to a function (e.g. the constructor of an exception object).

  1. I am using C++11, but portability is potentially an issue, so knowing which methods work and don't work in which versions of C++ would be a plus.

Edit

  1. For my immediate usage, I'm not concerned about performance (I'm raising an exception for cryin' out loud!). However, knowing the relative performance of the various methods would be very very useful in general.

  2. Why not just use printf itself (C++ is a superset of C after all...)? This answer discusses some reasons why not. As far as I can understand, type safety is a big reason: if you put %d, the variable you put in there had better really be convertible to an integer, as that's how the function figures out what type it is. It would be much safer to have a method which uses compile-time knowledge of the actual type of the variables to be inserted.

C++ Solutions


Solution 1 - C++

In C++20 you will be able to use std::format.

This will support python style formatting:

string s = std::format("{1} to {0}", "a", "b");

There is already an implementation available: https://github.com/fmtlib/fmt.

Solution 2 - C++

Method 1: Using a string stream

It looks like std::stringstream gives a quick solution:

std::stringstream ss;
ss << "error! value was " << actualValue << " but I expected " <<  expectedValue << endl;

//example usage
throw MyException(ss.str())

Positive

  • no external dependencies
  • I believe this works in C++ 03 as well as c++ 11.

Negative

  • reportedly quite slow
  • a bit more messy: you must create a stream, write to it, and then get the string out of it.

Method 2: Boost Format

The Boost Format library is also a possibility. Using this, you would do:

throw MyException(boost::format("error! value was %1% but I expected %2%") % actualValue % expectedValue);

Positive

  • pretty clean compared to stringstream method: one compact construct

Negative

  • reportedly quite slow: uses the stream method internally
  • it's an external dependency

Edit:

Method 3: variadic template parameters

It seems that a type-safe version of printf can be created by using variadic template parameters (the techincal term for a template that takes an indefinite number of template parameters). I have seen a number of possibilities in this vein:

  • This question gives a compact example and discusses performance problems with that example.
  • This answer to that question, whose implementation is also quite compact, but reportedly still suffers from performance issues.
  • The fmt library, discussed in this answer, is reportedly quite fast and seems to be as clean as printf itself, but is an external dependency

Positive

  • usage is clean: just call a printf-like function
  • The fmt library is reportedly quite fast
  • The other options seem quite compact (no external dependency required)

Negative

  • the fmt library, while fast, is an external dependency

  • the other options apparently have some performance issues

Solution 3 - C++

In C++11 you can use std::to_string:

"error! value was " + std::to_string(actualValue) + " but I expected " + std::to_string(expectedValue)

It's not pretty, but it's straightforward, and you can use a macro to shrink it a bit. Performance is not great, since you do not reserve() space beforehand. Variadic templates would probably be faster and look nicer.

This kind of string construction (instead of interpolation) is also bad for localization, but you'd probably use a library if you needed that.

Solution 4 - C++

Use whatever you like:

  1. std::stringstream

    #include std::stringstream ss; ss << "Hello world!" << std::endl; throw std::runtime_error(ss.str());

  2. libfmt : https://github.com/fmtlib/fmt

    #include throw std::runtime_error( fmt::format("Error has been detected with code {} while {}", 0x42, "copying"));

Solution 5 - C++

DISCLAIMER:
The subsequent code is based on an article I read 2 years ago. I will find the source and put it here ASAP.

This is what I use in my C++17 project. Should work with any C++ compiler supporting variadic templates though.

Usage:

std::string const word    = "Beautiful";
std::string const message = CString::format("%0 is a %1 word with %2 characters.\n%0 %2 %0 %1 %2", word, "beautiful", word.size()); 
// Prints:
//   Beautiful is a beautiful word with 9 characters. 
//   Beautiful 9 Beautiful beautiful 9.

The class implementation:

/**
 * The CString class provides helpers to convert 8 and 16-bit
 * strings to each other or format a string with a variadic number
 * of arguments.
 */
class CString
{
public:
    /**
     * Format a string based on 'aFormat' with a variadic number of arbitrarily typed arguments.
     *
     * @param aFormat
     * @param aArguments
     * @return
     */
    template <typename... TArgs>
    static std::string format(
            std::string const&aFormat,
            TArgs        &&...aArguments);

    /**
     * Accept an arbitrarily typed argument and convert it to it's proper
     * string representation.
     *
     * @tparam TArg
     * @tparam TEnable
     * @param aArg
     * @return
     */
    template <
            typename TArg,
            typename TEnable = void
            >
    static std::string toString(TArg const &aArg);

    /**
     * Accept a float argument and convert it to it's proper string representation.
     *
     * @tparam TArg
     * @param arg
     * @return
     */
    template <
            typename TArg,
            typename std::enable_if<std::is_floating_point<TArg>::value, TArg>::type
            >
    static std::string toString(const float& arg);


    /**
     * Convert a string into an arbitrarily typed representation.
     *
     * @param aString
     * @return
     */
    template <
            typename TData,
            typename TEnable = void
            >
    static TData const fromString(std::string const &aString);


    template <
            typename TData,
            typename std::enable_if
                     <
                        std::is_integral<TData>::value || std::is_floating_point<TData>::value,
                        TData
                     >::type
            >
    static TData fromString(std::string const &aString);
   
private:
    /**
     * Format a list of arguments. In this case zero arguments as the abort-condition
     * of the recursive expansion of the parameter pack.
     *
     * @param aArguments
     */
    template <std::size_t NArgs>
    static void formatArguments(std::array<std::string, NArgs> const &aArguments);

    /**
     * Format a list of arguments of arbitrary type and expand recursively.
     *
     * @param outFormatted
     * @param inArg
     * @param inArgs
     */
    template <
            std::size_t NArgs,
            typename    TArg,
            typename... TArgs
            >
    static void formatArguments(
            std::array<std::string, NArgs>     &aOutFormatted,
            TArg                              &&aInArg,
            TArgs                          &&...aInArgs);
};
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <typename... TArgs>
std::string CString::format(
        const std::string     &aFormat,
        TArgs             &&...aArgs)
{
    std::array<std::string, sizeof...(aArgs)> formattedArguments{};

    formatArguments(formattedArguments, std::forward<TArgs>(aArgs)...);

    if constexpr (sizeof...(aArgs) == 0)
    {
        return aFormat;
    }
    else {
        uint32_t number     = 0;
        bool     readNumber = false;

        std::ostringstream stream;

        for(std::size_t k = 0; k < aFormat.size(); ++k)
        {
            switch(aFormat[k])
            {
            case '%':
                readNumber = true;
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                // Desired behaviour to enable reading numbers in text w/o preceding %
                #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
                if(readNumber)
                {
                    number *= 10;
                    number += static_cast<uint32_t>(aFormat[k] - '0');
                    break;
                }
            default:
                if(readNumber)
                {
                    stream << formattedArguments[std::size_t(number)];
                    readNumber = false;
                    number     = 0;
                }

                stream << aFormat[k];
                break;
                #pragma GCC diagnostic warning "-Wimplicit-fallthrough"
            }
        }

        if(readNumber)
        {
            stream << formattedArguments[std::size_t(number)];
            readNumber = false;
            number     = 0;
        }

        return stream.str();
    }
}
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <typename TArg, typename enable>
std::string CString::toString(TArg const &aArg)
{
    std::ostringstream stream;
    stream << aArg;
    return stream.str();
}
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <
        typename TArg,
        typename std::enable_if<std::is_floating_point<TArg>::value, TArg>::type
        >
std::string CString::toString(const float& arg)
{
    std::ostringstream stream;
    stream << std::setprecision(12) << arg;
    return stream.str();
}
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <std::size_t argCount>
void CString::formatArguments(std::array<std::string, argCount> const&aArgs)
{
    // Unused: aArgs
}
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <std::size_t argCount, typename TArg, typename... TArgs>
void CString::formatArguments(
        std::array<std::string, argCount>     &outFormatted,
        TArg                                 &&inArg,
        TArgs                             &&...inArgs)
{
    // Executed for each, recursively until there's no param left.
    uint32_t const index = (argCount - 1 - sizeof...(TArgs));
    outFormatted[index] = toString(inArg);

    formatArguments(outFormatted, std::forward<TArgs>(inArgs)...);
}
//<-----------------------------------------------------------------------------

//<-----------------------------------------------------------------------------
//<
//<-----------------------------------------------------------------------------
template <
        typename TData,
        typename std::enable_if
                 <
                    std::is_integral<TData>::value || std::is_floating_point<TData>::value,
                    TData
                 >::type
        >
TData CString::fromString(std::string const &aString)
{
    TData const result{};

    std::stringstream ss(aString);
    ss >> result;

    return result;
}
//<-----------------------------------------------------------------------------

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstochasticView Question on Stackoverflow
Solution 1 - C++Stephan DollbergView Answer on Stackoverflow
Solution 2 - C++stochasticView Answer on Stackoverflow
Solution 3 - C++Peter TsengView Answer on Stackoverflow
Solution 4 - C++Vyacheslav NapadovskyView Answer on Stackoverflow
Solution 5 - C++MABVTView Answer on Stackoverflow