Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to use variadic function template in C++

2 Answers

0 votes
#include <iostream>

void print() {
    std::cout << "void print()";
}
 
template <typename T, typename... Types>
void print(T var, Types... args) {
    std::cout << "var: " << var << "\n";
 
    print(args...);
}
 
int main() {
    print(9, 324, 98.73, 7178, "c++");
    std::cout << "\n-----\n";
    print(5);
    std::cout << "\n-----\n";
    print();
}





/*
run:

var: 9
var: 324
var: 98.73
var: 7178
var: c++
void print()
-----
var: 5
void print()
-----
void print()

*/

 



answered Dec 6, 2022 by avibootz
0 votes
#include <iostream>

template<typename T>
T f(T v) {
    return v;
}

template<typename T, typename... Args>
T f(T first, Args... args) {
    return first + f(args...);
}
 
int main() {
    long sum = f(1, 2, 3, 4);

    std::cout << sum << "\n";
}





/*
run:

10

*/

 



answered Dec 6, 2022 by avibootz

Related questions

1 answer 91 views
91 views asked Dec 6, 2022 by avibootz
1 answer 106 views
2 answers 162 views
162 views asked Dec 10, 2020 by avibootz
1 answer 162 views
1 answer 127 views
127 views asked Mar 14, 2018 by avibootz
3 answers 212 views
...