3

Is it possible in C++ to write this:

template <typename T, size_t dim, size_t len>
using A = /* something */;

that will make these two lines equivalent:

/* 1 */ A<int, 3, 5> a;   A<char, 5, 3> c;

/* 2 */ int a[5][5][5];   char c[3][3][3][3][3];

?

1
  • 1
    Please explain more about "equivalent". Maybe show some lines of code you want to work and what effect you want them to have. Commented Nov 18, 2017 at 7:45

1 Answer 1

5

Is it possible? Yes, you can do arbitrarily complex calculations at compile-time, so there certainly is a solution.

The most straightforward way is to just use template recursion, like so:

template <class T, size_t dim, size_t len>
struct A_helper {
    using type = typename A_helper<T, dim - 1, len>::type[len];
};

template <class T, size_t len>
struct A_helper<T, 0, len> {
    using type = T;
};

template <class T, size_t dim, size_t len>
using A = typename A_helper<T, dim, len>::type;

See it on Coliru: http://coliru.stacked-crooked.com/a/bfc9052b30bce553

Sign up to request clarification or add additional context in comments.

3 Comments

Can I directly use template<typename T, size_t dim, size_t len> using A = A<T, dim-1, len>[len]?
i.e. is a helper class necessary?
@iBug You need something you can partially specialize in order to provide the base case, and alias templates cannot be (partially or wholly) specialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.