Search code examples
c++c++11variadic-functionsstd-function

std::function with C variadic arguments, not templated variable arguments


I basically want to do the following:

typedef
std::function<int(const char* format, ...)> PrintfLikeFunction;

However, that does not seem to work.

Is that possible? I really need to match functions with variadic arguments in my case so that I could pass in printf.

The other reason is, I want to have

void doSomething(PrintfLikeFunction logger);

and the implementation should be separate, thus this must not be a template function.


Solution

  • This isn't possible with std::function.

    It's pretty much impossible to forward C-style variadic arguments directly, without knowing what arguments were actually passed.

    Depending on the circumstances, you might just take a function pointer - a int(*)(const char*, ...), or, if type erasure is necessary, rework your code to use the variant taking a va_list.