Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer-lists as parameters for class constructor

I have a following class

template <class T>
class Graph {
    private:
        std::vector < std::vector<T> > data;
    public:
        class Edge {
            private:
                T source;
                T destination;
        };
};

I will be trying to model digraph using edge-centric approach (https://stackoverflow.com/a/2157012/1864702).

I want to be able to construct objects of this class in a following way:

enum Country {Poland, Ukraine, Germany, USA};
typedef Graph<Country> GC;

GC gc{
    { Poland, {Ukraine, Germany} },
    { Germany, {Poland, Ukraine, USA} },
    { USA, {Poland, Ukraine, USA} }
};

What kind of arguments should constructor of class Graph take to allow such a syntax?

like image 807
Mateusz Kowalski Avatar asked Jun 27 '26 13:06

Mateusz Kowalski


1 Answers

You can add a helper class into Graph and take an initializer list of these helper structs:

template <class T>
class Graph {
    private:
        std::vector < std::vector<T> > data;
        struct EdgeConstructor
        {
            T source;
            std::vector<T> destination;
        };
    public:
        class Edge {
            private:
                T source;
                T destination;
        };
        Graph(std::initializer_list<EdgeConstructor>) {}
};

Live example

like image 52
Angew is no longer proud of SO Avatar answered Jun 29 '26 03:06

Angew is no longer proud of SO