Iterating over a parameter pack??

Apr 1, 2016 at 5:37pm
Hi,

I have this:

1
2
3
4
5
6
7
8
9
template <typename... T_values>
class Thing {

    void something_else(T_values... values) {
	for (auto&& x : values... ) {
	     std::cout << x << std::endl;
	}
     }
}


The compiler (MSVC 2015) is giving me the following error:
error C3520: 'values': parameter pack must be expanded in this context


I thought this could work... Is it possible somehow?

Regards,
Juan
Last edited on Apr 1, 2016 at 5:37pm
Apr 1, 2016 at 6:19pm
1
2
3
for (auto&& x : { values... }) {
		std::cout << x << std::endl;
	}
Apr 1, 2016 at 8:00pm
this does not compile on Visual Studio 2015 Update 2...

any workarounds?
Apr 1, 2016 at 8:59pm
auto is used to automatically deduce the type but here you are asking it to be multiple different types which could make sense in a scripting language but not in a statically typed language like C++.

The only way I know of to iterate through a parameter pack is to use recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T>
void print(T value) {
	std::cout << value << std::endl;
}

template <typename First, typename... Rest>
void print(First firstValue, Rest... rest) {
	print(firstValue);
	print(rest...);
}

template <typename... T_values>
class Thing {

	void something_else(T_values... values) {
		print(values...);
	}
};
Apr 1, 2016 at 9:11pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

template <typename... T_values>
struct Thing {
    void something_else(T_values... values) {
		const int a[] = {(std::cout << values << ' ', 0)...};
		static_cast<void>(a);
    }
};

int main() {
	Thing<int, char, std::string> thing;
	thing.something_else(2, 'a', "hello");  // 2 a hello
}


When C++17 comes out, you can write as a binary right fold:
1
2
3
4
template<typename ...Args>
void print(Args&&... args) {
    (std::cout << ... << args) << '\n';
}

Last edited on Apr 1, 2016 at 9:15pm
Topic archived. No new replies allowed.