fork(3) download
  1. #include <utility>
  2. #include <iostream>
  3.  
  4.  
  5. template <int N, typename FirstArg, typename... Args>
  6. struct NthArgHelper {
  7. static_assert(N > 0, "N should be positive");
  8. static_assert(N < sizeof...(Args) + 1, "N is too large");
  9.  
  10. typedef typename NthArgHelper<N - 1, Args...>::Type Type;
  11.  
  12. static Type&& get(FirstArg&&, Args&&... args) {
  13. return NthArgHelper<N - 1, Args...>::get(args...);
  14. }
  15. };
  16.  
  17. template <typename FirstArg, typename... Args>
  18. struct NthArgHelper<0, FirstArg, Args...> {
  19. typedef FirstArg Type;
  20.  
  21. static Type&& get(FirstArg&& arg, Args&&...) {
  22. return std::forward<FirstArg>(arg);
  23. }
  24. };
  25.  
  26. template <int N, typename... Args>
  27. typename NthArgHelper<N, Args...>::Type&& NthArg(Args&&... args)
  28. {
  29. return NthArgHelper<N, Args...>::get(args...);
  30. }
  31.  
  32. template <typename... Args>
  33. void test(Args&&... args) {
  34. std::cout << "Argument 2: " << NthArg<2>(args...) << std::endl;
  35. std::cout << "Argument 0: " << NthArg<0>(args...) << std::endl;
  36. }
  37.  
  38. int main() {
  39. test(10, 3.1415, "Hello!");
  40. std::cout << "=======================\n";
  41. test(1, 2, 3, 7, 9, 5, 6, 6);
  42. return 0;
  43. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
Argument 2: Hello!
Argument 0: 10
=======================
Argument 2: 3
Argument 0: 1