2014-09-18 15 views
14

này đoạn mã:Tại sao enums không thể được sử dụng làm đối số trong constructor vector này?

enum {N = 10, M = 100}; 

vector<int> v(N, M); 

thất bại trong việc biên dịch với Visual Studio 2013, do các lỗi sau:

error C2838: 'iterator_category' : illegal qualified name in member declaration

Có gì sai với nó?

+2

Cả gcc và tiếng kêu đều ổn với điều này, có vẻ như là lỗi. –

+0

Tôi mạnh mẽ nghi ngờ lỗi của VS .. –

Trả lời

12

Đó là lỗi trong cả VS2012 và VS2013 vì nó không tuân thủ tiêu chuẩn C++ 11 (với _HAS_CPP0X được định nghĩa là 1):

C++ 03 23.1.1 [lib.sequence.reqmts]/9 nói:

For every sequence defined in this clause and in clause 21:

— the constructor template <class InputIterator> X(InputIterator f, InputIterator l, const Allocator& a = Allocator()) shall have the same effect as:

X(static_cast<typename X::size_type>(f), static_cast<typename X::value_type>(l), a) if InputIterator is an integral type.

nhưng từ 11 23.2.3 C++ [sequence.reqmts]/14:

For every sequence container defined in this Clause and in Clause 21:

— If the constructor template <class InputIterator> X(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type()) is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.

Đó constructor không nên được xem xét ở tất cả

More đây: https://stackoverflow.com/a/12432482/1938163

Để giải quyết sự cố, bạn có thể "giúp giải quyết quá tải một chút", ví dụ:

std::vector<int> v(static_cast<std::vector<int>::size_type>(N), M); 
10

Kể từ C++ 11 vector constructor chấp nhận hai InputIterators nên bị vô hiệu hóa nếu hai đối số là không lặp. VS2013 không thực hiện được điều này một cách chính xác.

2

Đây là một Visual Studio 2013 lỗi, từ lỗi được tạo ra (see it live), đây chỉ là một phần nhỏ:

[...]

see reference to function template instantiation 'std::vector>::vector<,void>(_Iter,_Iter)' being compiled

[...]>

Nó đang cố gắng sử dụng các nhà xây dựng mà phải mất hai vòng lặp đầu vào. Mà sẽ là một lỗi, cả hai gccclang là tốt với mã này.

Chúng ta có thể thấy trong 11 that constructor C++ không nên coi:

Constructs the container with the contents of the range [first, last). This constructor does not participate in overload resolution if InputIt does not satisfy InputIterator, to avoid ambiguity with the overload 2 (since C++11)

này phù hợp với dự thảo C++ 11 phần 23.2.3container Trình tự chuẩn đoạn mà nói:

If the constructor

template <class InputIterator> 
X(InputIterator first, InputIterator last, 
    const allocator_type& alloc = allocator_type()) 

is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.

Các vấn đề liên quan