我有一个叫做Shape
的类,它可以从任何可迭代的类中被初始化,并且一个名为Array
的类只包含一个Shape
。但是,我得到一个编译错误,当我尝试初始化Array
我无法解释:使用std :: initializer_list构造函数而不产生歧义?
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}; // ok
Array a1({1, 2}); // ok
Array a2({0}); // error
}
上的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()) {}
~~~~~~^~~
我不不要理解这里发生的事情。为什么调用Iterable
构造函数而不是initializer_list<T>
构造函数? Shape
构造函数与{0}
和Array
构造函数有什么区别?
我无法复制;你的代码在我的g ++ 6.3.0和我的clang ++ 3.8.1(我的意思是......如果你更正了'NDShape',对于第二个构造函数,在'Shape'中编译得很好)。你正在使用哪种编译器? – max66
你说得对,对不起。我简化了代码太多。更新的代码现在应该会给你一个错误。谢谢! – AstrOne
现在我有一个错误,但它与您所报告的完全不同;你可以确认“没有匹配函数调用'cbegin(const int&)[...]”错误吗? – max66