I currently have 2 function overloads:
void log(const char* format, ...);
void log(const string& message);
and I want that in case of this call: log("hello");
the string version will be called, or in other words the first overload should only be called in case of 2 arguments or more.
I thought about doing this:
template<typename T>
void log(const char* format, T first, ...);
but in this case I will have trouble using va_list
properly in the code.
Is there any other solution I might be missing?
EDIT:
I thought about checking the size of va_list
from inside the function, and redirecting in case of 0, but as far as I understood it's impossible to get the size of va_list
.
log(std::string{"hello})
. But this isn't really what you seem to want.In either of the functions, call the other one.
But it's not very efficient because you'll have a useless
string
object, although the compiler may be able to inline the call.Use variadic templates and SFINAE:
The second overload will be available in the set of candidate functions only if there're trailing arguments. Showcase. In C++14, you can use the short-hand version of
std::enable_if
,std::enable_if_t
, which makes the syntax clearer:You can still simplify it in C++11 by using
If you're calling a function which accepts a
va_list
(such asprintf
) you're still able to expand the pack of parameters:but not vice versa.