I have a class called Shape
that can be initialized from any iterable and a class with a name Array
that just contains Shape
. However, I get a compilation error, which I cannot explain when I try to initialize Array
:
class Shape
{
public:
template<typename Iterator>
Shape(Iterator first, Iterator last)
: m_shape(first, last) {}
template <typename Iterable>
Shape(const Iterable& shape)
: Shape(shape.begin(), shape.end()) {}
template<typename T>
Shape(std::initializer_list<T> shape)
: Shape(shape.begin(), shape.end()) {}
private:
std::vector<std::size_t> m_shape;
};
class Array
{
public:
Array(const Shape& shape)
: m_shape(shape) {}
private:
Shape m_shape;
};
int main() {
Shape s{0};
Array a1({1, 2});
Array a2({0});
}
A compilation error appears in the second constructor Shape
:
prog.cxx:35:16: required from here
prog.cxx:14:23: error: request for member ‘begin’ in ‘shape’, which is of non-class type ‘const int’
: Shape(shape.begin(), shape.end()) {}
~~~~~~^~~~~
prog.cxx:14:38: error: request for member ‘end’ in ‘shape’, which is of non-class type ‘const int’
: Shape(shape.begin(), shape.end()) {}
~~~~~~^~~
I don’t understand what is going on here. Why is a constructor initializer_list<T>
called instead of a constructor Iterable
? What is the difference between a constructor Shape
with {0}
and a constructor Array
?
source
share