c++ - std::for_each 使用 g++ 编译错误,而不是 VS2012

标签 c++ visual-c++ c++11 g++

我有以下代码(尽可能简化):

#include <vector>
#include <algorithm>

using std::vector;

enum class Foo {
    BAR, BAZ
};

void print_to_file(const vector<const vector<Foo> >& sequences) {
    std::for_each(sequences.begin(), sequences.end(), [](const vector<Foo>& sequence) {
    });
}

int main(int argc, char **argv) {
    return EXIT_SUCCESS;
}

当使用 g++ (SUSE Linux) 4.7.1 20120723 [gcc-4_7-branch revision 189773] 编译为 g++ --std=c++11 test.cpp 我收到以下错误消息:

In file included from /usr/include/c++/4.7/x86_64-suse-linux/bits/c++allocator.h:34:0,
                 from /usr/include/c++/4.7/bits/allocator.h:48,
                 from /usr/include/c++/4.7/vector:62,
                 from test.cpp:1:
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of ‘struct __gnu_cxx::new_allocator<const std::vector<Foo> >’:
/usr/include/c++/4.7/bits/allocator.h:89:11:   required from ‘class std::allocator<const std::vector<Foo> >’
/usr/include/c++/4.7/bits/alloc_traits.h:89:43:   required from ‘struct std::allocator_traits<std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/ext/alloc_traits.h:109:10:   required from ‘struct __gnu_cxx::__alloc_traits<std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/bits/stl_vector.h:76:28:   required from ‘struct std::_Vector_base<const std::vector<Foo>, std::allocator<const std::vector<Foo> > >’
/usr/include/c++/4.7/bits/stl_vector.h:208:11:   required from ‘class std::vector<const std::vector<Foo> >’
test.cpp:11:25:   required from here
/usr/include/c++/4.7/ext/new_allocator.h:83:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const std::vector<Foo>; __gnu_cxx::new_allocator<_Tp>::const_pointer = const std::vector<Foo>*; __gnu_cxx::new_allocator<_Tp>::const_reference = const std::vector<Foo>&]’ cannot be overloaded
/usr/include/c++/4.7/ext/new_allocator.h:79:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const std::vector<Foo>; __gnu_cxx::new_allocator<_Tp>::pointer = const std::vector<Foo>*; __gnu_cxx::new_allocator<_Tp>::reference = const std::vector<Foo>&]’

相同的代码在 VS2012 上编译得很好,但在 g++ 下却严重失败,我完全不知道如何解释错误消息。

最佳答案

我很惊讶你没有在其他地方遇到问题,因为这个 vector<const vector<Foo> >不是可能的数据类型。

std::vector 的值类型必须至少是可复制构造的 (C++03) 或可移动的 (C++11)。如果它是 const,则不能分配或移动它。

关于c++ - std::for_each 使用 g++ 编译错误,而不是 VS2012,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909017/

相关文章:

windows - 使用 VC++ Express 2010 编译 libdwarf 无法运行 Demo 应用程序

qt - 在 Qt Creator 上构建时,jom 挂起 - MSVC 2008 Express

c++ - 为什么我收到错误 'A<int>' 不是基类的基类的 'S<int>' 的可访问基?

c++ - 在 C++ 中将函数指针转换为仿函数

c++ - 自动工具检查 C++11

c++ - OSX 10.7.5 上的 node-gyp -- dyld : lazy symbol binding failed: Symbol not found

c++ - sub2Ind matlab 到 c++/opencv 的转换

visual-c++ - 在 OpenGL 中的纹理顶部显示 2D 形状

c# - 褪色的正确数学是什么?

c++ - 没有重复的随机数组生成