Group template options in C ++

I build an algorithm independent of the number of dimensions, where the number of dimensions is a template parameter. I have several input data and the number of output measurements.

For 5 input measurements and 3 output dimensions, ideally, it looks like this:

my_algorithm<5, 3> algo;

However, I very often need a sum of input and output measurements. So what I came up with:

template <size_t IDims, size_t ODims = 3, size_t Dims = IDims + ODims>
class my_algorithm;

Thus, the total number of measurements is also a compile time constant. Note that the most common scenario has only 3 output dimensions, so I put this as the default argument. This allows me to be very pleased:

my_algorithm<5> algo;

However, I do not have this very long template signature, which I must write for each method in this class. For instance:

template <size_t IDims, size_t ODims, size_t Dims>
my_algorithm<IDims, ODims, Dims>::prepare(size_t k, size_t Kcap) {
    m_Kcap = Kcap;
    m_pi = new float[Kcap]{1.0f / k};
}

, , - . - :

#include <cstdio>

template<size_t IDims, size_t ODims = 3>
struct Dims {
    static constexpr size_t I = IDims;
    static constexpr size_t O = ODims;
    static constexpr size_t A = I + O;
};

template<typename D>
void function() {
    std::printf("function() with Dims<%zu, %zu, %zu>\n", D::I, D::O, D::A);
}

int main() {
    function<Dims<2, 4>>();
    function<Dims<2>>();
    return 0;
}

(typename D), , , , Dims.

+4
1

, . , , , ++ 17, constexpr static Dims . . , constexpr :

template<typename D>
void my_algo<D>::some_function(size_t number) {
    constexpr DA = D::A;
    Eigen::Matrix<float, D::A, Eigen::Dynamic> vector (DA, number);
    //                   ^^^^                          ^^
    //                   works                 here D::A doesn't work
}

D::A , . ++ 17 static constexpr, , .

0

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


All Articles