jeudi 1 août 2019

How to use a const reference as template parameter?

I am trying to implement a kind of matrix wrapper that takes a container of a container as template parameter.

But I get an error when trying to construct a matrix_wrapper of a const reference. The code seems to work with a non reference, non pointer, not const parameter and I would like to use the same code for both cases. Even though I'll have another template specialization for pointers.

When I try to compile this code I get the following errors:

>c:\users\emedeiros\source\repos\test\test\test.cpp(240): error C2079: 'matrix' uses undefined class 'matrix_wrapper<const std::vector<std::vector<double,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>> &>'
1>        with
1>        [
1>            _Ty=double
1>        ]
1>c:\users\emedeiros\source\repos\test\test\test.cpp(240): error C2440: 'initializing': cannot convert from 'const std::vector<std::vector<double,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>>' to 'int'
1>        with
1>        [
1>            _Ty=double
1>        ]
1>c:\users\emedeiros\source\repos\test\test\test.cpp(240): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1


Below you'll find the class definition and a function that will try to create a matrix_wrapper.

template <class T>
class matrix_wrapper;

template <typename T, class A1, class A2, template <typename, typename> class Cont1, template <typename, typename> class Cont2>
class matrix_wrapper < Cont2 < Cont1 < T, A1>, A2> >
{
public:
    typedef typename boost::call_traits<Cont2<Cont1<T, A1>, A2>>::value_type value_type;
    typedef typename boost::call_traits<value_type>::param_type param_type;
    typedef typename boost::call_traits<value_type>::reference reference;

    typedef Cont1<T, A1> vector_type;
    typedef typename boost::call_traits<vector_type>::reference vector_type_ref;
    typedef typename boost::call_traits<vector_type>::const_reference vector_type_const_ref;
    typedef T data_type;

    matrix_wrapper(reference data) : m_data(data) {}

    inline vector_type_const_ref operator[](size_t i) const
    {
        return m_data[i];
    }

    inline vector_type_ref operator[](size_t i)
    {
        return m_data[i];
    }

    inline reference data()
    {
        return m_data;
    }

protected:
    reference m_data;
};


void test(const std::vector<std::vector<double>>& data)
{
    matrix_wrapper<const std::vector<std::vector<double>>&> matrix(data);
}

What do I have to change so I can use a const reference as parameter?

Aucun commentaire:

Enregistrer un commentaire