V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cxxnullptr
V2EX  ›  C++

可变参数模板,递归获取参数时,如何确定当前参数是第几个?

  •  
  •   cxxnullptr · 2022-08-22 17:54:14 +08:00 · 1204 次点击
    这是一个创建于 584 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下:

    #include <iostream>
    
    template <typename T, typename... Args>
    void print(const T &text, Args... args) {
        std::cout << text << ' ';
        std::cout << ??? << std::endl;  // 如何获取参数的索引位置?
    
        if constexpr (sizeof...(args) > 0) {
            print(args...);
        }
    }
    
    int main(int argc, char *argv[])
    {
        print("abc", "def", "ghi");
    
        return 0;
    }
    
    

    期望输出:

    abc 1
    def 2
    ghi 3
    
    5 条回复    2022-08-22 19:33:09 +08:00
    flysp
        1
    flysp  
       2022-08-22 18:01:58 +08:00
    template <int N, typename T, typename... Args>
    void real(const T &text, Args... args) {
    std::cout << N << " " << text << std::endl;

    if constexpr (sizeof...(args) > 0) {
    real<N + 1>(args...);
    }
    }

    template <typename T, typename... Args>
    void print(const T &text, Args... args) {
    real<0>(text, args...);
    }

    int main()
    {
    print("hello, world", "bonjour", "je'la ");
    }
    fgwmlhdkkkw
        2
    fgwmlhdkkkw  
       2022-08-22 18:02:30 +08:00
    可以自己做个变量,+1 往下传吧
    ysc3839
        3
    ysc3839  
       2022-08-22 18:23:28 +08:00
    C++17 的话可以这么写:
    ```
    template <typename... Args>
    void print(Args... args) {
    size_t i = 0;
    ((std::cout << args << ' ' << ++i << std::endl), ...);
    }
    ```
    https://en.cppreference.com/w/cpp/language/fold
    cxxnullptr
        4
    cxxnullptr  
    OP
       2022-08-22 19:32:27 +08:00
    @flysp
    @ysc3839 感谢两位老哥
    cxxnullptr
        5
    cxxnullptr  
    OP
       2022-08-22 19:33:09 +08:00
    @fgwmlhdkkkw 涉及模板的就不太会写了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3482 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:58 · PVG 18:58 · LAX 03:58 · JFK 06:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.