Question about varargs

Hey guys!

So, I just read a good article on using var_lists. I was wondering if there was a way to check if another argument exists in a list. Does anyone know how to do that?
No. You will have to know from previous arguments if there are more to read or not.
... and you must assert the type (thus size) of each argument. There's nothing in the variable arg mechanism to tell you what's there.
Ok, well thanks anyways :D
If you are programming in C++, prefer type-safe mechanisms:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

template < typename T > inline
std::ostream& print( std::ostream& stm, const T& value ) { return stm << value ; }

template < typename FIRST, typename... REST > inline
std::ostream& print( std::ostream& stm, const FIRST& first, REST... rest )
{ return print( print( stm, first ), rest... ) ; }

int main()
{
    print( std::cout, "the value is: ", 12345, '\n' ) ;
    print( std::cout, "the values are: ", 12345, ", ", 78.32, " and ", 999, '\n' ) ;
}

JLBorges: In my opinion, it's much easier to use nested insertion(cout<<something<<somethingelse<<yadday<<"Hello World";)
> In my opinion, it's much easier to use nested insertion

The print() was for expositional purposes, to provide a type-safe alternative to a C function using va_list - fprintf()

It is a matter of opinion all right. Any function which can be written to take a variable number of arguments can be replaced with nested calls to an appropriately written binary function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <type_traits>
#include <iostream>

template < typename T, typename U > inline
typename std::common_type<T,U>::type plus( const T& a, const U& b ) { return a+b ; }

template < typename FIRST, typename... REST > inline
typename std::common_type<FIRST,REST...>::type plus( const FIRST& first, REST... rest )
{ return first + plus( rest... ) ; }

int main()
{
    std::cout << plus( 'a', 500, 1234.56, 99ULL ) << '\n' ;
    std::cout << plus( 'a', plus( 500, plus( 1234.56, 99ULL ) ) ) << '\n' ;
}
Topic archived. No new replies allowed.