Variadic function: Difference between revisions

No edit summary
(→‎{{header|C}}: Added C++)
Line 143:
 
The actual implementation of <tt>va_list</tt> is implementation-dependent. If you are developing on a specific platform, you may use platform-specific knowledge to create a <tt>va_list</tt> by hand in a non-portable way. For example, on many platforms, a <tt>va_list</tt> is simply a pointer to a buffer where the arguments are arranged contiguously in memory.
 
=={{header|C++}}==
The C++ varargs are basically the same as in C (therefore you can just take the code from C), but there are some limitations:
* Only PODs (basically, every type you could also write in C) can be passed to varargs
* An important difference is that enums are distinct types with possibly different representation that int in C++, but enumeration values are still converted to <code>int</code> when passed to varargs. Therefore they have to accessed as <code>int</code> in <code>va_arg</code>.
 
The next version of C++ will in addition allow typesafe variadic arguments through variadic templates. Some compilers, such as gcc, already provide this functionality. The following implements the tast with variadic templates:
 
{{works with|g++|4.3.0}} using option -std=c++0x
 
<lang cpp>
#include <iostream>
 
template<typename T>
void print(T const& t)
{
std::cout << t;
}
 
template<typename First, typename ... Rest>
void print(First const& first, Rest const& ... rest)
{
std::cout << first;
print(rest ...);
}
 
int main()
{
int i = 10;
std::string s = "Hello world";
print("i = ", i, " and s = \"", s, "\"\n");
}
</lang>
As the example shows, variadic templates allow any type to be passed.
 
=={{header|C sharp|C#}}==
973

edits