[QUESTION] Advanced default parameters function

Hello everbody,

I'm asking how to create a function with default parameters with the possibility to init the parameters that you need.

Code Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int func(int a = 1, int b = 2, int c = 3, int d = 4)
{
   return a + b * c / d;
}

int main(int ac, char** av)
{
   (void)ac;
   (void)av;

   std::cout << func(b = 42, d = 31) << std::endl;
   std::cout << func(12, d = 28) << std::endl;
   std::cout << func(d = 1, c = 2, b = 3, d = 4) << std::endl;
}


Does someone could solve my problem?
Last edited on
In what I understood, it is not possible supported in C++
Last edited on
There is no support for named parameters, but it is possible to emulate them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Foo {
  int a_, b_, c_, d_;
public:
  Foo() : a_(1), b_(2), c_(3), d_(4) {}
  Foo & a( int x ) { a_ = x; return *this; }
  Foo & b( int x ) { b_ = x; return *this; }
  Foo & c( int x ) { c_ = x; return *this; }
  Foo & d( int x ) { d_ = x; return *this; }
  int eval() { return a_ + b_ * c_ / d_; }
};

int main()
{
   std::cout << Foo().eval() << std::endl;
   std::cout << Foo().b( 42 ).d( 31 ).eval() << std::endl;
   std::cout << Foo().a( 12 ).d( 28 ).eval() << std::endl;
   std::cout << Foo().d( 1 ).c( 2 ).b( 3 ).a( 4 ).eval() << std::endl;
  return 0;
}

Topic archived. No new replies allowed.