Convert int array to variational pattern

Let's say I have an int array, for example int arr[N], and they say that it arr[i]is from a tiny domain (for example, 1-10). Say I also have a variation template with a common interface (abstract class)

template <int... A>
class FooImpl : public Foo
{
}

The question is how to implement the function:

Foo* getFoo(int arr[N]);

or maybe better:

Foo* getFoo(int* pint, int size);

which would return FooImplwith template arguments matching my array? For example, for arr = {4,2,6,1}I would getFooImpl<4,2,6,1>

+4
source share
2 answers

. , . _getFoo_impl struct func, .

, [1-5] <= 4, :

class Foo
{
};

template <int...A>
class FooImpl : Foo {
};

template<int...As>
struct _getFoo_impl
{
    static Foo* func(int *arr, int sz)
    {
        if (sz == 0)
            return new FooImpl<As...>;

        switch (*arr)
        {
        case 1: return _getFoo_impl<As..., 1>::func(arr + 1, sz - 1);
        case 2: return _getFoo_impl<As..., 2>::func(arr + 1, sz - 1);
        case 3: return _getFoo_impl<As..., 3>::func(arr + 1, sz - 1);
        case 4: return _getFoo_impl<As..., 4>::func(arr + 1, sz - 1);
        case 5: return _getFoo_impl<As..., 5>::func(arr + 1, sz - 1);
        default: throw "element out of range";
        }
    }
};

template<int A1, int A2, int A3, int A4, int A5>
struct _getFoo_impl<A1, A2, A3, A4, A5>
{
    static Foo* func(int*, int sz) {
        std::terminate();
    }
};

Foo* getFoo(int *arr, int size)
{
    return _getFoo_impl<>::func(arr, size);
}
+1

template <int... N>
class FooImpl;

. , ,

template <int... N>
R FooFun(A...);

, , R(A...) . , A... ; , . FooFun(int, int).

, , factory , FooImpl<N...>, Foo*, FooFun

template <int... N>
Foo* FooFun();

non-constexpr (, , , ), - ).

, . ""

template <int OFFSET>
R FooDispatch(A...);

. FooDispatch. OFFSET N... . , , , . N..., FooDispatch FooFun<N...>(...).

, , Matlab ind2sub, . , , , . , , .

, ,

Foo* getFoo(int arr[N]);

,

Foo* getFoo(int* pint, int size);

; , , , .

, , , C.

0

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


All Articles