variadic templates same number of function arguments as in class

前端 未结 2 1214
面向向阳花
面向向阳花 2021-02-08 03:49

How to define method signature so it will accept same number of arguments as variadic template class definition? For example how to define an Array class:

2条回答
  •  渐次进展
    2021-02-08 03:55

    template
    class Array {
      templateusing index_t=int; // can change this
    public:
      T& operator()(index_t... is);
    };
    

    or:

    template
    class Array {
    public:
      T& operator()(decltype(Shape)... is);
    };
    

    or:

    template
    class Array {
    public:
      T& operator()(decltype(Shape, int())... is);
    };
    

    if you want to be able to change the type of the parameter to be different than Shape.

    I find the decltype harder to understand a touch than the using, especially if you want to change the type of the parameter to be different than int.

    Another approach:

    template
    class Array {
    public:
      template::type>
      T& operator()(Args&&... is);
    };
    

    which uses SFINAE. It does not enforce that the Args are integer types however. We could add another clause if we wanted to (that all of the Args are convertible to int, say).

    Yet another approach is to have your operator() take a package of values, like a std::array. Callers would have to:

    Array arr;
    arr({0,0,0});
    

    use a set of {}s.

    A final approach would be:

    template
    class Array {
    public:
      template
      auto operator()(Args&&... is) {
        static_assert( sizeof...(Args)==sizeof...(Shapes), "wrong number of array indexes" );
      }
    };
    

    where we accept anything, then generate errors if it is the wrong number of arguments. This generates very clean errors, but does not do proper SFINAE operator overloading.

    I would recommend tag dispatching, but I don't see a way to make it much cleaner than the SFINAE solution, with the extra decltype and all, or better error messages than the static_assert version on the other hand.

提交回复
热议问题