+ 3

How do I declare a variadic function in C++

Sorry for this simple question I'm still somewhat new to C++

22nd Apr 2019, 8:20 AM
ScriptingEngine
ScriptingEngine - avatar
6 ответов
+ 4
Variadic templates (C++11) https://en.cppreference.com/w/cpp/language/parameter_pack https://en.wikipedia.org/wiki/Variadic_template C style variadic functions are to be avoided in C++. Example: #include <iostream> // Base case, just like in recursion template<typename T> T sum( T value ) { return value; } // Variadic function template<typename T, typename... Args> T sum( T value, Args... args ) { return value + sum( std::forward<Args>(args)... ); // return value + sum( args... ); should be ok as well here. } int main() { std::cout << sum( 1, 3, 4, 3 ); }
22nd Apr 2019, 8:31 AM
Dennis
Dennis - avatar
+ 3
here is an example without using recursion: https://code.sololearn.com/cp7M3NWL9A9P/#cpp
22nd Apr 2019, 2:15 PM
MO ELomari
MO ELomari - avatar
+ 2
How about initializer_list<T>?
22nd Apr 2019, 2:23 PM
HonFu
HonFu - avatar
+ 1
MOIN KHAN That's not a variadic function, m8.
22nd Apr 2019, 12:54 PM
Dennis
Dennis - avatar
0
Simply make a function and pass variable arguments to it using function overloading like int example(int a, int b) {. . . return(i,j)}
22nd Apr 2019, 12:52 PM
MOIN KHAN
MOIN KHAN - avatar
0
May i can be wrong
22nd Apr 2019, 12:56 PM
MOIN KHAN
MOIN KHAN - avatar