How to reverse the order of arguments of a variadic template function?

前端 未结 5 1160
猫巷女王i
猫巷女王i 2020-11-27 16:42

I have a template function with varargs template arguments, like this

template
void ascendingPrint(         


        
5条回答
  •  伪装坚强ぢ
    2020-11-27 17:27

    I think instead of reversing the arguments, you can reverse your logic! For example reverse the operations on arguments.

    template 
    void ascendingPrint(const T& x)
    {
        cout << x << " ";
    }
    
    template
    void ascendingPrint(const T& t, Args... args)
    {
        ascendingPrint(t);                   // First print `t`
        ascendingPrint(args...);             // Then print others `args...`
    }
    
    template 
    void descendingPrint(const T& x)
    {
        cout << x << " ";
    }
    
    template
    void descendingPrint(const T& t, Args... args)
    {
        descendingPrint(args...);            // First print others `args...`
        descendingPrint(t);                  // Then print `t`
    }
    
    int main()
    {
        ascendingPrint(1, 2, 3, 4);
        cout << endl;
        descendingPrint(1, 2, 3, 4);
    }
    

    Output

    1 2 3 4 
    4 3 2 1 
    

提交回复
热议问题