2012-02-27 46 views
3

我有一個3D陣列double s。我想編寫簡單的&通用函數來打印它的2D切片。如何將Boost.MultiArray的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>

如何編寫可以工作的原型?

+0

可能的重複[哪裏,爲什麼我必須把「模板」和「typename」關鍵字?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have -to-put-the-template-and-typename-keywords) – Xeo 2012-02-28 00:35:44

回答

1

我無法拼出C++類型推斷失敗的確切原因,但將函數原型更改爲template<class M> void printFloatMatrix(const M& matrix)。儘管如此,原型無用地廣泛。很有可能它會在未來咬我。這種情況有望在概念出現時得到解決,或者可以用靜態斷言進行解決。

感謝在Freenode的##c++

+4

任何時候你有'typename X :: Y',你都有一個所謂的「不可誘發的上下文」,這意味着沒有模板參數可以從爲該參數傳遞參數。您需要在呼叫站點指定類型,更改不可推理的上下文(如您在此處所做的那樣),或者提供允許模板參數推演的另一個參數。 – Xeo 2012-02-28 00:35:11

+0

這必須與模板的圖靈完備性和暫停問題相關。謝謝,現在我明白了。 – ulidtko 2012-02-28 11:16:20

相關問題