astrophobia
astrophobia

Reputation: 889

function with variable number of arguments that are converted to a string

I am interested in creating a C++ function that takes a variable number of arguments, where each argument can be of an arbitrary type (I just know that it is valid to convert each argument value to a string using std::to_string()) and creating a string with all the parameter values concatenated in a single string. How can this be done in C++11? I have found some ways of doing the conversion when the types are known a priori (see below for example) but it is not clear to me how this can be done if the type is not known a priori.

void simple_printf(const char* fmt...)
{
    va_list args;
    va_start(args, fmt);

    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            std::cout << i << '\n';
        } else if (*fmt == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            std::cout << static_cast<char>(c) << '\n';
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            std::cout << d << '\n';
        }
        ++fmt;
    }

    va_end(args);
}

Upvotes: 0

Views: 315

Answers (1)

rmawatson
rmawatson

Reputation: 1935

if its just concatenation, and only types that std::to_string is defined for,

#include <iostream>
#include <array>
#include <numeric>
#include <string>

template <typename...Ts>
std::string make_string(const Ts&... args)
{
    std::array<std::string,sizeof...(args)> values{ std::to_string(args)...};
    return std::accumulate(values.begin(),values.end(),std::string{});
}

int main() {
    std::cout << make_string(1,2.0d,3.0f) << std::endl;
    return 0;
}

Demo

Upvotes: 2

Related Questions