I'm trying to create map[per] sort of code, but i'm looking for a more simpler way of coding a constructor.
An example:
#define B {0, 0, 0, 0, 1}
struct A {
A(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0) {
this->args[0] = a;
this->args[1] = b;
this->args[2] = c;
this->args[3] = d;
this->args[4] = e;
};
~A() {};
int args[5];
};
By more simpler I mean something like:
#define C { {},{},{},{} }
struct B {
B(){};
int d,e;
char f,g;
}
struct A {
A(B b[] = {}) { };
B strct[4];
}
A a = C;
Which I just can't get to work.
CodePudding user response:
If I'm understanding correctly, You're trying to find an easier way to construct class A:
struct A
{
A(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0)
: args{a, b, c, d, e} {};
~A(){};
int args[5];
};
We can use braces to initialize array int[5].
CodePudding user response:
You could use a variadic template like...
struct A {
template <typename... T>
A(T... a) : args{a...} {};
int args[5];
};
int main() {
A a1(1); // Initializes only the first element individually; others get default initialized (zero-initialized)
A a2(1,2); // first two elements get initialized individually
// A a6(1,2,3,4,5,6); // Error: Excess elements in array initializer
}
CodePudding user response:
One option (C 11 and later) use an initializer_list. For example;
#include <initializer_list>
#include <algorithm>
struct A
{
A(std::initializer_list<int> values) : args {0}
{
if (values.size() < 5)
std::copy(values.begin(), values.end(), args);
}
int args[5];
};
int main()
{
A a{1,2,3}; // note the values are in curly braces
for (int v : a.args) std::cout << v << ' ';
std::cout << '\n';
}
The args{0} in the initialiser list of the constructor initialises all elements of args to zero, and the loop accepts up to five values in the initiliser list. If there are more than five values supplied, all are ignored in the above.
If you want to use the arguments to create a container with an arbitrary number of int, you can do also use a standard container, such as vector.
#include <initializer_list>
#include <vector>
struct A
{
A(std::initializer_list<int> values) : args(values)
{
}
std::vector<int> args;
};
// same main() as above.
In this case, the number of elements in a.args (i.e. a.args.size()) will be the same as that supplied (no trailing zeros, unless explicitly supplied).
