variadic templates same number of function arguments as in class

前端 未结 2 1204
面向向阳花
面向向阳花 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 T, int...Shape>
    class Array {
      template<int>using index_t=int; // can change this
    public:
      T& operator()(index_t<Shape>... is);
    };
    

    or:

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

    or:

    template<class T, int...Shape>
    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 T, int...Shape>
    class Array {
    public:
      template<class...Args,class=typename std::enable_if<sizeof...(Args)==sizeof...(Shape)>::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<sizeof...(Shape), int>. Callers would have to:

    Array<double, 3,2,1> arr;
    arr({0,0,0});
    

    use a set of {}s.

    A final approach would be:

    template<class T, int...Shape>
    class Array {
    public:
      template<class...Args>
      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.

    0 讨论(0)
  • I assume you want your arguments to be all of the same type, probably using an integer type (I'll just use int). An easy approach is to leverage the parameter pack you already have:

    template <int>
    struct shape_helper { typedef int type; };
    
    template <typename T, int... Shape>
    class Array
    {
    public:
        T& operator()(typename shape_helper<Shape>::type...);
    }; 
    
    0 讨论(0)
提交回复
热议问题