簡體   English   中英

如何通過引用相同的模板函數傳遞一行boost :: multi_array和std :: vector?

[英]How to pass a row of boost::multi_array and std::vector by reference to the same template function?

我對這段代碼有問題:

#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>]'

當我將函數foo的第一個參數的類型從Vec&更改為Vec ,它對boost :: multi_array起作用,但是std :: vector按值傳遞,這不是我想要的。 如何在不編寫兩個模板的情況下實現目標?

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

一個(不太好)解決方案將是如下所示:

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:: version;

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM