What is the correct type for join_rows ()?

I wrote a function that concatenates the strings of two 2D arrays :

template <typename S, typename T>
Array<typename S::Scalar, Dynamic, Dynamic> join_rows(const ArrayBase<S> & A, const ArrayBase<T> & B) {
    Array<typename S::Scalar, Dynamic, Dynamic> C (A.rows(), A.cols()+B.cols());
    C << A, B;
    return C;
}

I would like to write a more general function that can be combined with more than two arrays.

It should be able to work with any iterable container, for example. std::listor std::vector, therefore, I would use the template paragraph template.

I can easily hide the body of the function with two cycles, which is not a problem, I'm just trying to figure out what the correct type for such a function will be.

(ps. I'm not even sure my code above is of a better type, but it seems to do the job)

+4
source share
1 answer

, Array s, , , . , :

// end case (one argument): just forward the same array
template <typename T>
T&& join_rows(T&& A) {
    return std::forward<T>(A);
}

// main function template: two or more arguments
template <typename S, typename T, typename... R>
Array<typename S::Scalar, Dynamic, Dynamic> join_rows(const ArrayBase<S>& A,
                                                      const ArrayBase<T>& B,
                                                      const ArrayBase<R>&... rest) {
    Array<typename S::Scalar, Dynamic, Dynamic> C(A.rows(), A.cols()+B.cols());
    C << A, B;
    return join_rows(C, rest...); // call with the first two arguments combined
}

:

int main() {
    Array<int, 1, 3> arr1 = {1, 2, 3};
    Array<int, 1, 2> arr2 = {4, 5};
    Array<int, 1, 4> arr3 = {9, 8, 7, 6};

    cout << join_rows(arr1, arr2, arr3.reverse()) << endl; // 1 2 3 4 5 6 7 8 9

    return 0;
}

join_rows Eigen::Array s, std::enable_if ArrayBase<T>:

template <typename T>
std::enable_if_t<std::is_base_of<ArrayBase<std::decay_t<T>>,std::decay_t<T>>::value, T&&>
join_rows(T&& A) {
    return std::forward<T>(A);
}

Array s . , -, Array.

+2

Source: https://habr.com/ru/post/1651549/


All Articles