How to make so that in function it was possible to transfer a variable number of parameters of one type ?

  • 2
    The question is good, but a duplicate of this. Stackoverflow.com/questions/419928/… - Alex.B
  • Your question is not very accurate. Do you need exactly the template function? Or the usual also come down? - Harry
  • @Harry is particularly confused by the title of the question. Those. The author already knows the answer. - αλεχολυτ
  • @ Alex.B in that question in the answers are different types, not one - erbber
  • @erbber, well, take the one that fits)) - Alex.B

3 answers 3

For example, like this:

template<typename T> void foo(std::initializer_list<T>) 
  • it would be normal, but it’s necessary {} to set - erbber

A possible solution for any number of identical types that does not require to specify curly brackets when calling:

 #include <iostream> template<typename T, typename... Types> void foo(T t, Types... types) { for(auto&& e: { t, types... }) { std::cout << e << " "; } std::cout << "\n"; } int main() { foo("hello", ",", "world"); foo(1, 2, 3, 4, 5); //foo(1, "hello"); // error } 
  • Kmk, initializer_list immediately in for would be better. Fewer entities and an optimizer are simpler. - Abyx
  • @Abyx really. Now I'll fix it. - αλεχολυτ

Option with compilation error if the arguments do not match:

 #include <iostream> #include <type_traits> template<class ...Args> struct Dummy{}; template<class T, class ...Args, class = Dummy<typename std::enable_if<std::is_same<T, Args>::value>::type...>> void foo(const T &arg, const Args &...args){ } int main(){ int i = 0; double d = 0; foo(i, i); //ok foo(d, d); //ok //foo(i, d); //error }