templates - c++ va_list function overload -
i have 2 function overloads:
void log(const char* format, ...); void log(const string& message);
and want in case of call: log("hello");
string version called, or in other words first overload should called in case of 2 arguments or more.
i thought doing this:
template<typename t> void log(const char* format, t first, ...);
but in case have trouble using va_list
in code.
is there other solution might missing?
edit: thought checking size of va_list
inside function, , redirecting in case of 0, far understood it's impossible size of va_list
.
- force type construction:
log(std::string{"hello})
. isn't seem want. in either of functions, call other one.
void log(const string& s) { log(s.c_str()); }
but it's not efficient because you'll have useless
string
object, although compiler may able inline call.use variadic templates , sfinae:
void log(const string&); auto log(const char *ptr, args&& ... args) -> typename std::enable_if<sizeof...(args) != 0, void>::type
the second overload available in set of candidate functions if there're trailing arguments. showcase. in c++14, can use short-hand version of
std::enable_if
,std::enable_if_t
, makes syntax clearer:auto log(const char *ptr, args&& ... args) -> std::enable_if_t<sizeof...(args) != 0, void>
you can still simplify in c++11 using
template <bool b, typename t> using enable_if_t = typename std::enable_if<b, t>::type;
if you're calling function accepts va_list
(such printf
) you're still able expand pack of parameters:
std::printf(ptr, args...);
but not vice versa.
Comments
Post a Comment