user1899020
user1899020

Reputation: 13575

How to let list can convert to my class object implicitly?

For example, I have a class Point and has a function

void foo(Point pt);

call it as

foo({1, 2, 3});

Upvotes: 3

Views: 107

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69892

#include <initializer_list>
#include <cassert>

struct bar
{
    void foo(const std::initializer_list<int>& bits)
    {
        assert(bits.size() == 3);
        auto i = bits.begin();
        x = *i++;
        y = *i++;
        z = *i++;
    }

    int x, y, z;
};

int main()
{
    bar b;
    b.foo({0, 1, 2});
}

Upvotes: 3

Artur Pyszczuk
Artur Pyszczuk

Reputation: 1940

You have to have constructor which takes three ints. Consider:

struct Point {
    Point (int p1_, int p2_, int p3_) : p1 {p1_}, p2 {p2_}, p3 {p3_} {}

    int p1;
    int p2;
    int p3;
};

void foo (Point pt) {
    std::cout << pt.p1 << std::endl;
    std::cout << pt.p2 << std::endl;
    std::cout << pt.p3 << std::endl;
}

and usage:

foo ({1, 2, 3});
std::cout << std::endl;
foo ({4, 5, 6});

Upvotes: -2

Related Questions