2010-01-24 9 views
5

我有這段代碼的問題:如何通過引用相同的模板函數傳遞一行boost :: multi_array和std :: vector?

#include <boost/multi_array.hpp> 
#include <boost/array.hpp> 
#include <vector> 
#include <iostream> 

template <typename Vec> 
void foo(Vec& x, size_t N) 
{ 
    for (size_t i = 0; i < N; ++i) { 
     x[i] = i; 
    } 
} 

int main() 
{ 
    std::vector<double> v1(10); 
    foo(v1, 5); 
    std::cout << v1[4] << std::endl; 


    boost::multi_array<double, 2> m1; 
    boost::array<double, 2> shape; 
    shape[0] = 10; 
    shape[1] = 10; 
    m1.resize(shape); 
    foo(m1[0], 5); 
    std::cout << m1[0][4] << std::endl; 
    return 0; 
} 

試圖用GCC編譯它,我得到的錯誤:

boost_multi_array.cpp: In function 'int main()': 
boost_multi_array.cpp:26: error: invalid initialization of non-const reference of type 'boost::detail::multi_array::sub_array<double, 1u>&' from a temporary of type 'boost::detail::multi_array::sub_array<double, 1u>' 
boost_multi_array.cpp:7: error: in passing argument 1 of 'void foo(Vec&, size_t) [with Vec = boost::detail::multi_array::sub_array<double, 1u>]' 

它如預期提升工程:: multi_array中當我改變函數foo的第一個參數的類型從Vec&Vec,但隨後std :: vector按值傳遞,這不是我想要的。如何在不編寫兩個模板的情況下實現我的目標?

回答

1

問題是,對於NumDims> 1operator[]返回template subarray<NumDims-1>::type類型的臨時對象。

A(不是很好)的變通將是類似以下內容:

typedef boost::multi_array<double, 2> MA; 
MA m1; 
MA::reference ref = m1[0]; 
foo(ref, 5); // ref is no temporary now 

另一種方法是來包裝您的實現,並提供了多陣列情況下的過載....例如:

(注:我沒有看到如何讓超載與boost::multi_array<T,N>::reference工作,請不要把它投入生產使用這種detail::版本;)

template<class T> 
void foo_impl(T x, size_t N) { 
    for (size_t i = 0; i < N; ++i) { 
     x[i] = i; 
    } 
} 

template<class T> 
void foo(T& t, size_t n) { 
    foo_impl<T&>(t, n); 
} 

template<typename T, size_t size> 
void foo(boost::detail::multi_array::sub_array<T, size> r, size_t n) { 
    foo_impl(r, n); 
} 
+0

這可以使用boost :: enable_if_c和boost :: traits來優雅地解決嗎? – 2010-01-25 21:11:16

+0

MA :: reference ref = m1 [0]行絕對不是語法上的簡潔,但它不會在運行時爲std :: vector情況添加大量開銷。我最近碰到了同樣的問題:http://old.nabble.com/-multiarray--problems-passing-views-by-reference-td27039405.html – 2010-01-26 04:59:33

+0

@quant_dev:這也有問題,爲什麼使用'boost :: multi_array :: reference'直接不起作用,我沒有時間進一步調查。 – 2010-01-26 13:21:09

相關問題