私は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()) {}
~~~~~~^~~
私は「ドンここで起こっていることを理解する。 initializer_list<T>
コンストラクタの代わりにIterable
コンストラクタが呼び出されるのはなぜですか? {0}
とArray
コンストラクタのShape
コンストラクタの違いは何ですか?
私は再現できません。私のg ++ 6.3.0と私のclang ++ 3.8.1とで、あなたのコードはうまくコンパイルされます( 's5'行にエラーはありません)。第2のコンストラクタの' NDShape'を 'Shape' )。どのコンパイラを使用していますか? – max66
あなたは正しいです、申し訳ありません。コードをあまりにも単純化しました。更新されたコードでエラーが発生するはずです。ありがとう! – AstrOne
今私はエラーがありますが、あなたが報告したものとはまったく異なります。あなたは "cbegin(const int&)[...]"呼び出しのための "no matching function"を確認できますか? – max66