Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put parameters for different functions inside an array in C++?

Tags:

c++

So in Python I can do something like

def f1(a, b):
    print("sum", a + b)

def f2(str1, str2):
    print("min len str", min(len(str1), len(str2)))

def f3(a,b,c,d):
    print("product", a*b*c*d)

functions = [f1, f2, f3]
params = [(1,2),('test str', 'testdtr'), (1,2,4,3)]
for i in range(len(functions)):
    functions[i](*(params[i]))

Output:

sum 3
min len str 7
product 24

Is there a way to achieve this in C++?

like image 546
qwerty_99 Avatar asked Dec 06 '25 07:12

qwerty_99


1 Answers

In C++, data must be typed. This makes the syntax heavier but allows control during the compilation phase.
To store entities of different types, the container to use is the tuple.

To traverse the tuple, we cannot use the for. The iterations are made with the index_sequence object (to make indices), and a pack expansion (to apply each indice).
To call functions using tuple in place of parameters, we need apply().
We can define the iteration in place using a lambda template immediately instantiated and called ([]<>(){}()).

import  std;

auto  f1( double a, double b ) {
   endl( std::cout << "sum " << a + b);
}
auto   f2( std::string_view str1, std::string_view str2 ) {
   endl( std::cout << "min len str " << std::min(size(str1),size(str2)) );
}
auto  f3( double a, double b, double c, double d ) {
   endl( std::cout << "product " << a * b * c * d );
}

int  main() {
   auto functions = std::tuple{ f1,f2,f3 };
   auto params = std::tuple{
         std::tuple{1,2},
         std::tuple{"test str", "testdtr"},
         std::tuple{1,2,4,3}
      };

   [&]<size_t...I>( std::index_sequence<I...> ){
         (std::apply( std::get<I>(functions), std::get<I>(params) ), ...);
      }( std::make_index_sequence<3>{} );
}

Use std::tuple{1,2,3}, in place of std::tuple{1,2}, and the compilation fails. All is checked at compilation time.

like image 198
dalfaB Avatar answered Dec 12 '25 15:12

dalfaB