代码之家  ›  专栏  ›  技术社区  ›  quant_dev

如何通过引用同一模板函数来传递一行boost::multi_数组和std::vector?

  •  5
  • quant_dev  · 技术社区  · 16 年前

    我对这段代码有一个问题:

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

    当我更改函数的第一个参数的类型时,它与boost::multi_数组的预期一样工作 foo 从…起 Vec& Vec

    1 回复  |  直到 10 年前
        1
  •  1
  •   Georg Fritzsche    16 年前

    问题是,对于 NumDims>1. operator[] 返回类型为的临时对象 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:: 版本;)

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