fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. template<typename Ret>
  5. Ret foo(const char *,int);
  6. template<>
  7. std::string foo<std::string>(const char *s,int) { return s; }
  8. template<>
  9. int foo<int >(const char *,int i) { return i; }
  10.  
  11.  
  12. #include<tuple>
  13.  
  14. template<size_t num_args, typename ...T>
  15. class Foo;
  16. template<typename ...T>
  17. class Foo<2,T...> : public std::tuple<T&&...>
  18. {
  19. public:
  20. Foo(T&&... args) :
  21. std::tuple<T&&...>(std::forward<T>(args)...)
  22. {}
  23. template< typename Return >
  24. operator Return() { return foo<Return>(std::get<0>(*this), std::get<1>(*this)); }
  25. };
  26. template<typename ...T>
  27. class Foo<3,T...> : std::tuple<T&&...>
  28. {
  29. public:
  30. Foo(T&&... args) :
  31. std::tuple<T&&...>(std::forward<T>(args)...)
  32. {}
  33. template< typename Return >
  34. operator Return() { return foo<Return>(std::get<0>(*this), std::get<1>(*this), std::get<2>(*this)); }
  35. };
  36.  
  37. template<typename ...T>
  38. auto
  39. auto_foo(T&&... args)
  40. // -> Foo<T&&...> // old, incorrect, code
  41. -> Foo< sizeof...(T), T&&...> // to count the arguments
  42. {
  43. return {std::forward<T>(args)...};
  44. }
  45.  
  46.  
  47.  
  48.  
  49. int main() {
  50. std::string s = auto_foo("hi",5); std::cout << s << std::endl;
  51. int i = auto_foo("hi",5); std::cout << i << std::endl;
  52. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
hi
5