2

私は次のコードを持っています(可能な限り単純化されています):

#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 ++でひどく失敗し、エラーメッセージを解釈する方法が少しもわかりません。

4

2 に答える 2

5

vector<const vector<Foo> >これは可能なデータ型ではないため、他の場所で問題が発生しないことに驚いています。

mustのvalue_typeは、std::vector少なくともコピー構成可能(C ++ 03)または移動可能(C ++ 11)である必要があります。constの場合、割り当てたり移動したりすることはできません。

于 2012-10-16T07:28:07.387 に答える
3

const標準コンテナに使用されるアロケータ要件では、オブジェクトをコンテナに保持することはできません。C ++ 11 17.6.3.5「アロケータ要件」は、表27で始まる一連のテーブルを使用した標準アロケータの要件の概要を示しています。表27では、最初の定義は「記述変数」、、、TおよびUとしてC定義されています。非定数、非参照オブジェクトタイプ」。アロケータクラスの定義に使用される記述変数Xとは、次のとおりです。Y

X-タイプのアロケータクラスT

Y-タイプに対応するアロケータクラスU

要約すると、標準のアロケータは、非定数型によるパラメータ化の観点から定義されています。

これには、2004年に遡る古いGCC / libstdc ++バグがあります(無効として解決されました)(C ++ 2003には、constオブジェクトをコンテナーに格納することに対して同様の制限がありますが、2003標準では、コンテナに格納されるオブジェクトは「割り当て可能」である必要があります)。

于 2012-10-16T08:03:10.963 に答える