overloading - Undefined number of arguments in C++ -


this question has answer here:

can overload function lot of arguments in javascript. example:

function f() {   alert(arguments[0]); }  f(4); // alert 4  

can same thing in c++ ?

you can use variadic template arguments , tuples:

#include <tuple> #include <iostream>  template <class... args> void f(args&&... args) {     auto arguments = std::make_tuple(std::forward<args>(args)...);     std::cout << std::get<0>(arguments); }  void f() {} // 0 arguments  int main() {     f(2, 4, 6, 8); } 

live demo

for bounds checking, try following:

#include <tuple> #include <iostream>  template <class... t> struct input {     std::tuple<t...> var;     input(t&&... t) : var(std::forward<t>(t)...) {}      template <std::size_t n, bool in_range = 0 <= n && n < std::tuple_size<decltype(var)>::value>     auto get() -> typename std::tuple_element<in_range ? n : 0, std::tuple<t...>>::type     {         return std::get<in_range ? n : 0>(var);     } };  template <class... args> void f(args&&... args) {     auto arguments = input<args...>(std::forward<args>(args)...);      std::cout << arguments.template get<9>(); }  void f() {} // 0 arguments  int main() {     f(2, 4, 6, 8); } 

update: if need first argument want function exposes first argument separating parameter pack:

template<class head, class... tail> void foo(head&& head, tail&&... tail); 

if not satisfactory (i.e want nth-argument), can unpack arguments std::tuple<> , retrieve element std::get<>:

template<class... args> void foo(args&&... args) {     auto t = std::forward_as_tuple(std::forward<args>(args)...);     print(std::get<5>(t)); } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -