3

の3D配列がありdoubleます。2Dスライスを印刷するためのシンプルでジェネリックな関数を書きたいです。

コード:

#include <cstdio>
#include <boost/multi_array.hpp>

template<class M> // any model of MultiArray concept
void printFloatMatrix(typename M::template array_view<2u>::type matrix) {
    using std::printf;

    for(auto& row : matrix) {
        for(auto& elem : row) {
            printf("%5.3f ", elem);
        }
        printf("\n");
    }
}


int main() {
    typedef boost::multi_array<double,3> data_t;
    data_t test_matrix{data_t::extent_gen()[10][10][2]};
    // ...

    using boost::indices;
    using boost::multi_array_types::index_range;
    printFloatMatrix(test_matrix[ indices[index_range()] [index_range()] [0] ]);
}

GCCでは、これによりエラーメッセージが生成されます。

test.cpp: In function ‘int main()’:
test.cpp:24:79: error: no matching function for call to ‘printFloatMatrix(boost::multi_array_ref<double, 3u>::array_view<2u>::type)’
test.cpp:24:79: note: candidate is:
test.cpp:5:6: note: template<class M> void printFloatMatrix(typename M::array_view<2u>::type)

なぜエラーですか?

なぜそう思われないMのですboost::multi_array_ref<double, 3u>か?

動作するプロトタイプを作成するにはどうすればよいですか?

4

1 に答える 1

1

ここで C++ の型推論が失敗する正確な理由を説明することはできませんが、関数プロトタイプを変更すると機能しtemplate<class M> void printFloatMatrix(const M& matrix)ます。

しかし、プロトタイプは今では無駄に広いです。高い確率で将来噛まれます。この状況は、コンセプトの出現によって修正されるか、代わりに静的アサートで回避できることが期待されます。

##c++Freenodeに感謝します。

于 2012-02-27T21:34:43.003 に答える