dimanche 7 février 2021

Is there a better way to implement the const version of member function row() without using const_cast?

The example comes from the demonstration for use of std::slice and std::slice_array:

https://en.cppreference.com/w/cpp/numeric/valarray/slice

https://en.cppreference.com/w/cpp/numeric/valarray/slice_array

How should I properly define the const version of member function row()? The following code compiles but it uses const_cast. I would really appreciated it if you can give any suggestion.

#include <iostream>
#include <valarray>
class Matrix {
    std::valarray<int> data;
    int dim;
 public:
    Matrix(int r, int c) : data(r*c), dim(c) {}
    int& operator()(int r, int c) {return data[r*dim + c];}
    std::slice_array<int> row(std::size_t row) {
        return data[std::slice(dim*row, dim, 1)];
    }
    const std::slice_array<int> row(std::size_t row) const {
        return const_cast<std::valarray<int>&>(data)[std::slice(dim*row, dim, 1)];
    }
};
int main()
{
    Matrix m(3,3);
    int n = 0;
    for(int r=0; r<3; ++r)
       for(int c=0; c<3; ++c)
           m(r, c) = ++n;
    
    const Matrix m2(m);

    for(int r=0; r<3; ++r) {
        for(int c=0; c<3; ++c) {
            std::cout << m(r, c) << " ";
        }
        std::cout << std::endl;
    }

    // non-const
    std::slice_array<int> isa = m.row(0);
    std::valarray<int> iva(isa);
    for (auto elem : iva) { std::cout << elem << std::endl;} 
    
    // const
    const std::slice_array<int> isa2 = m2.row(0);
    const std::valarray<int> iva2(isa2);
    for (auto elem : iva) { std::cout << elem << std::endl;} 

    return 0;
}

If the member function is defined as follows:

    const std::slice_array<int> row(std::size_t row) const {
        return data[std::slice(dim*row, dim, 1)];
    }

then following error message is produced:

valarray_demo.cpp:13:16: error: no viable conversion from returned value of type '__val_expr<__slice_expr<const std::__1::valarray<int> &> >' to function return type 'const std::slice_array<int>'
        return data[std::slice(dim*row, dim, 1)];
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/valarray:1149:28: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from
      '__val_expr<__slice_expr<const std::__1::valarray<int> &> >' to 'const std::__1::slice_array<int> &' for 1st argument
class _LIBCPP_TEMPLATE_VIS slice_array

test on: macOS Catalina; Apple clang version 11.0.3 (clang-1103.0.32.29)

Aucun commentaire:

Enregistrer un commentaire