Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple program using std::rotate not compile?

Tags:

c++

std

c++11

This does not work:

#include <algorithm>

int main()
{
    int a[] = { 1, 2, 3 };
    auto it = std::rotate(std::begin(a), std::begin(a) + 1, std::end(a));
}

The error I get is:

main.cpp:6:10: error: variable has incomplete type 'void'
    auto it = std::rotate(std::begin(a), std::begin(a) + 1, std::end(a));

This is clearly incorrect behavior, as the declaration of rotate is:

template<class ForwardIterator>
  ForwardIterator rotate(ForwardIterator first, ForwardIterator middle,
          ForwardIterator last);

Why does this simple program fail to compile?

like image 456
user4139575 Avatar asked Oct 14 '14 01:10

user4139575


2 Answers

Before C++11, std::rotate used to return void. So you're likely on a non C++11-compliant implementation.

like image 172
Alexander Gessler Avatar answered Nov 09 '22 07:11

Alexander Gessler


This looks like a libstdc++ issue we can see this by doing a test using both libstdc++ and libc++ and we can see it only fails when we are using libstdc++.

Using Rextesters online compilers makes doing a quick test pretty simple, the libc++ live version generates no errors. While the libstdc++ live version generates the following error:

error: variable has incomplete type 'void'

If we look at cppreference entry for std::rotate we can see the pre C++11 version indeed returned void:

template< class ForwardIt >
void rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ) (until C++11)

template< class ForwardIt >
ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ); (since C++11)

As indicated above in the comments this is apparently a known bug:

25.3  |   Mutating sequence operations  | Partial rotate  | returns void.

Also, perhaps worth noting Visual Studio has no problems with this code.

like image 35
Shafik Yaghmour Avatar answered Nov 09 '22 08:11

Shafik Yaghmour