Check template parameter pack for specific values

356 Views Asked by At

I am writing a small Tensor class, that should look like this:

using namespace std; // for simplicity
template<typename T, size_t N>
class Tensor {
    size_t rank_;
    array<int, N> size_;
    vector<T> data;
public:
    template<typename... Args>
    Tensor(Args... args) : rank_{ N }, size_{args...}, data((... * args), T{}) {
        static_assert(sizeof...(Args) == N, "Wrong number of indicies");
        static_assert(conjunction_v<is_integral<Args>...>, "Not an integer_type");
...

        

For the constructor I want to do a few compile-time checks to prevent errors:

  1. After the initialization I check whether the correct numbers of arguments (N) have been passed to the constructor (is there a way to enforce this check before the constructor initializes the data?

  2. I check whether the caller passes only integral data types to the constructor.

  3. I want to check whether all the passed values are larger than zero. I don't know how to implement the third condition. I tried something like

    static_assert(conjunction_v<bool_constant<(args > 0)>...>, "Index must be larger than zero!");

This code does not compile. I think, that static_assert might not even be usable here, because the actual sizes of the dimensions may be known at runtime rather than compile time. What is the best way to implement such a check on a parameter pack (at compile time when possible, else on runtime)? I initialize the array<int,N> size_ with the parameter pack, so in the constructor I could iterate over the array and check for the correct range. But is this the cleanest solution?

0

There are 0 best solutions below