0

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);
}
3
  • Using c++17 would be a problem? If not, i can answer. Commented Nov 3, 2019 at 0:44
  • It has to be C++11 max, cannot use C++17 Commented Nov 3, 2019 at 0:45
  • @astrophobia Do you just want to concatenate, or you want formatting? Commented Nov 3, 2019 at 0:54

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.