fork download
  1. #include <cstdio>
  2.  
  3. #include <string>
  4. #include <tuple>
  5. #include <utility>
  6.  
  7. template <typename T>
  8. struct get_specifier;
  9.  
  10. template <>
  11. struct get_specifier<int> {
  12. static constexpr char const* value = "%d";
  13. };
  14.  
  15. template <>
  16. struct get_specifier<char const*> {
  17. static constexpr char const* value = "%s";
  18. };
  19.  
  20. template <>
  21. struct get_specifier<double> {
  22. static constexpr char const* value = "%f";
  23. };
  24.  
  25. template <size_t, typename>
  26. struct format_runner;
  27.  
  28. template <size_t Index, typename... Ts>
  29. struct format_runner<Index, std::tuple<Ts...>> {
  30. using tuple_type = std::tuple<Ts...>;
  31.  
  32. template <typename String>
  33. static String execute(String&& init) {
  34. return format_runner<Index-1, tuple_type>::execute(std::forward<String>(init))
  35. + " "
  36. + get_specifier<
  37. typename std::tuple_element<Index, tuple_type>::type
  38. >::value;
  39. }
  40. };
  41.  
  42. template <typename... Ts>
  43. struct format_runner<0, std::tuple<Ts...>> {
  44. using tuple_type = std::tuple<Ts...>;
  45.  
  46. template <typename String>
  47. static String execute(String&& init) {
  48. return init + get_specifier<
  49. typename std::tuple_element<0, tuple_type>::type
  50. >::value;
  51. }
  52. };
  53.  
  54. template <typename String, typename... Ts>
  55. String format(String&& init, Ts&&... values) {
  56. return format_runner<
  57. sizeof...(Ts)-1,
  58. std::tuple<typename std::remove_reference<Ts>::type...>
  59. >::execute(std::forward<String>(init));
  60. }
  61.  
  62. template <typename... Ts>
  63. int redisCommand(char const* prefix, Ts&&... values) {
  64. return std::printf(
  65. format(std::string(prefix), values...).c_str(),
  66. values...
  67. );
  68. }
  69.  
  70. int main() {
  71. char const* value1 = "1";
  72. int value2 = 2;
  73. double value3 = 3.0;
  74.  
  75. redisCommand("SET foo ", value1, value2, value3);
  76. }
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
SET foo 1 2 3.000000