va_list with templates

Hi all,
I have this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdarg>

template < typename T >
void print( int numArgs, ... ) {
    va_list vl;
    va_start( vl, numArgs );

    for ( int i = 0; i < numArgs; i++ ) {
        T arg = va_arg( vl, T );
        std::cout << arg;
    }
}

int main( int argc, char* argv[] ) {
    print( 2, "Hello, ", " World!" );

    return 0;
}


When I compile it, I get the following error: error: no matching function for call to 'print(int, const char [8], const char [8])'
What is wrong with the code?

Thanks!
Last edited on
you need to provide the template parameter an line 16 because the compiler can't deduce it from the parameter
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

template < typename T > void print( const T& v ) { std::cout << v ; }

template < typename FIRST, typename... REST >
void print( const FIRST& first, const REST&... rest  ) { print(first) ; print( rest... ) ; }

int main()
{
    print( "Hello, ", " World!", ' ', 1234, '\n' ) ;
}

@coder777: so, if I'm right, the compiler needs to know the types of ... at compile time?

@JLBorges: your code doesn't compile, generates alot of errors because of the dots. Do I have to replace the three dots with something?
You need a C++11 compiler. If you have GCC, compile with -std=c++11

Or, online: http://liveworkspace.org/code/107aXl$0

See: http://en.wikipedia.org/wiki/Variadic_template
OK, right, I tried with Codepad :) Thank you!
[bump] But still the question: so, if I'm right, the compiler needs to know the types of ... at compile time? Is that true?
Yes. But with the first example you could simply...
print<const char *>( 2, "Hello, ", " World!" );
Last edited on
ah, thank you!
Topic archived. No new replies allowed.