You can use recursive templates and std::string::replace:
#include <iostream>
#include <string>
template<typename Arg>
void convertArgument(std::string &fmt, Arg arg) {
int location = fmt.find("%d");
fmt.replace(location, 2, arg);
}
template<>
void convertArgument(std::string &fmt, int arg) {
int location = fmt.find("%d");
fmt.replace(location, 2, std::to_string(arg));
}
template<typename Arg>
std::string convert(std::string fmt, Arg arg) {
convertArgument(fmt, arg);
return fmt;
}
template<typename Arg, typename... Args>
std::string convert(std::string fmt, Arg arg, Args... args) {
convertArgument(fmt, arg);
return convert(fmt, args...);
}
int main() {
std::cout << convert("%d - %d", "ABC", 123).c_str();
return 0;
}
For each argument one conversion is called until all arguments are embedded into the string. You can specialize the convertArgument
template for custom classes.
Add the end you can convert the string to a cstring.
4
solved How to replicate c++ printf function [closed]