代码如下:
#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
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 "); } |
2
fgwmlhdkkkw 2022-08-22 18:02:30 +08:00
可以自己做个变量,+1 往下传吧
|
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 |
4
cxxnullptr OP |
5
cxxnullptr OP @fgwmlhdkkkw 涉及模板的就不太会写了
|