How to pass different number of flags to function

Hi everybody

I put several checkboxes on the form to test function. Each checkbox represent one FLAG. My question is how to pass to function different number of flags each time ?

best regards
different number of flags each time

I'm not sure what you're trying to achieve but I think you want that part(parameter) dynamic. You can then check using a for loop and switch-case statements. Or use an observer type of pattern.
Create a small helper class to wrap your flags in and pass that to your function.
e.g.:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

class Flags
{
private:
	bool m_flag1;
	bool m_flag2;

public:
	Flags(bool flag1, bool flag2)
	{
		m_flag1 = flag1;
		m_flag2 = flag2;
	}

	bool getFlag1()
	{
		return m_flag1;
	}

	bool getFlag2()
	{
		return m_flag1;
	}
};

void FunctionToTakeMyFlags(Flags& flags)
{
	// get individual flags e.g.
	bool internalFlag1 = flags.getFlag1();

}

int main()
{
	bool checkBox1 = false;
	bool checkBox2 = true;

	Flags myFlags(checkBox1, checkBox2);

	FunctionToTakeMyFlags(myFlags);


	return 0;
}


or this class could have a vector of bools so you could add and remove from them if you have to decide the number of flags at runtime. e.g.
1
2
3
4
5
6
7
8
bool checkBox1 = false;
	bool checkBox2 = true;

	Flags myFlags;
        myFlags.add(checkBox1);
        myFlags.add(checkBox2);

	FunctionToTakeMyFlags(myFlags);
Last edited on
I put several checkboxes on the form to test function.

Each of those boxes is either checked or unchecked. In other words each flag is either true or false, but always present. As such, there is always the same number of flags.

It seems that each flag represents specific, named property. The function has to know the properties too.

1
2
3
4
5
6
7
8
9
10
enum class Flag { FOO, BAR };

void function( const std::map<Flag, bool> & flags ) {
  bool barstate { false }; // default
  auto flag = flags.find( BAR );
  if ( flags.end() != it ) {
    // state of bar was given
    barstate = *it;
  }
...
Pass a list of structures/classes with whatever data you want. eg:

1
2
3
4
5
6
7
8
9
struct xyz_t {
  std::string label;
  bool flag;
};

void function(const std::list<xyz_t>& flags)
{
  ...
}


As your requirement gets more complex you can increase the data in the structure/class, and add a constructor.
Last edited on
Topic archived. No new replies allowed.