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);
}
Aucun commentaire:
Enregistrer un commentaire