0

Environment is C++14 with clang and g++

I'm searching for something like

"Point somepoint = Point(X=23);"

where it is possible to define a value inside a class by calling the name of the variable and this should be done at the initialising.

here is a simplified code to explain my problem why i don't use other methods.

#include <iostream>
using namespace std;

class Point {
    public:
    int X{4};
        int Y{8};
        Point(){};
        Point(int x) : X{x} {};
        Point(int x, int y) : X{x}, Y{y} {};
};

int main() {
    const Point one = Point();
    const Point two = Point(23);
    const Point tri = Point(42,23);

    cout << "tri: \t" << tri.X << "\t" << tri.Y << endl;
    cout << "two: \t" << two.X << "\t" << two.Y << endl;
    cout << "one: \t" << one.X << "\t" << one.Y << endl;

}

There are some variables and every variable got a default value. I can define variable with different values but i will use most of the defaults. With 2 variables there are only 4 possibilities but my real code got over 16 variables.

I could use constructors. That does not work because of two same datatypes. The constructors Point(int X) and Point(int Y) can't be in the same class. A workaround would be to define own datatypes for every variable. This would work good with 2 variables but my real code has much more.

The easiest idea is to construct the class and then define the values. This will not work because one, two and tri are constants.

Point master = Point();
master.X = 33;
master.Y = 44;

One idea was to use templates and a custom datatype based on a string for the name and a value. But something like

Point(set("X",3), set("Y",42));

would be uglier and less readable than

Point( Y = 3, X = 42)

and the code with the implementation itself would be much less readable, too. In case of many variables its a significant problem.

I hope i explained my problem good enough and why i want to use names. Hopefully somebody got a solution for this.

best regards Paul

Sickeroni
  • 66
  • 6
  • 1
    Look into the [Named Parameter Idiom](https://isocpp.org/wiki/faq/ctors#named-parameter-idiom). – Fred Larson Apr 18 '16 at 21:24
  • See also [my answer](http://stackoverflow.com/a/2700976/10077) to a related question. – Fred Larson Apr 18 '16 at 21:26
  • You could also do almost as your example suggested: `Point somepoint = Point("X=23");` or `Point somepoint = Point("X=23, Y=200, Z=-4");` where the argument is a string expression that you parse and assign the various members. Of course you make up the rules of what constitutes a valid expression, but you get the idea. – PaulMcKenzie Apr 18 '16 at 21:28

0 Answers0