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

2022 年 8 月 22 日
 cxxnullptr

代码如下:

#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
2206 次点击
所在节点    C++
5 条回复
flysp
2022 年 8 月 22 日
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
2022 年 8 月 22 日
可以自己做个变量,+1 往下传吧
ysc3839
2022 年 8 月 22 日
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
2022 年 8 月 22 日
@flysp
@ysc3839 感谢两位老哥
cxxnullptr
2022 年 8 月 22 日
@fgwmlhdkkkw 涉及模板的就不太会写了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/874619

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX