Reputation: 85
I want my own class can be list-initialized like vector:
myClass a = {1, 2, 3};
How can I do that using C++11 capabilities?
Upvotes: 7
Views: 363
Reputation: 3203
An initializer_list
can be (like other STL containers) iterated and the size
can be queried. This allows you to do as pointed in the other answer by yuyoyuppe to immediately feed it to a vector
. But you may have other intents for your initialization and do something like execute an operation directly on the items of the list without copying.
#include <initializer_list>
#include <iostream>
#include <algorithm>
struct S
{
int thesum;
int items;
S(std::initializer_list<int> l) :
thesum(std::accumulate(l.begin(), l.end(), 0)),
items(l.size())
{}
};
int main()
{
S s = { 1, 2, 3 };
std::cout << s.items << std::endl;
std::cout << s.thesum << std::endl;
return 0;
}
This prints
3
6
See:
Upvotes: 1
Reputation: 1602
C++11 has a notion of initializer lists. To use it, add a constructor which accepts a single argument of type std::initializer_list<T>
. Example:
#include <vector>
#include <initializer_list>
#include <iostream>
struct S
{
std::vector<int> v_;
S(std::initializer_list<int> l)
: v_(l)
{
std::cout << "constructed with initializer list of length " << l.size();
}
};
int main()
{
S s = { 1, 2, 3 };
return 0;
}
Upvotes: 8