2012-02-27 43 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

相关问题