3

How do I redefine a call like this via C preprocessor Instructions to snprintf?

sprintf_s<sizeof(dataFile)>(dataFile, arg2, arg3);

I tried this (which doesn't work):

#define sprintf_s<sizeof(x)>(args...) snprintf<sizeof(x)>(args)

Especially because I already need this for calls to sprintf_s without a template in the same files:

#define sprintf_s(args...) snprintf(args)
EXIT_FAILURE
  • 278
  • 1
  • 13

2 Answers2

3

This is simply not supported by the preprocessor. The preprocessor is largely the same as the C preprocessor and C has no notion of templates.

mrks
  • 8,033
  • 1
  • 33
  • 62
2

As mkrs said in his/her answer, the preprocessor doesn't allow you to match template-like function invocations.

You don't need the preprocessor for this task - use a variadic template instead:

template <int Size, typename... Ts>
auto sprintf_s(Ts&&... xs)
{
    return snprintf<Size>(std::forward<Ts>(xs)...);
}

If snprintf uses va_arg, you will need a different kind of wrapper:

template <int Size>
void sprintf_s(char* s, ...)
{
    va_list args;
    va_start(args, s);
    snprintf(args);
    va_end(args);
}

See How to wrap a function with variable length arguments? for more examples.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • This unfortunately gives me the following compiler error: comparison of distinct pointer types ('int (*)(char *__restrict, size_t, const char *__restrict, ...) throw()' (aka 'int (*)(char *__restrict, unsigned long, const char *__restrict, ...) throw()') and 'int *') I have to admit that I only started out with templates and still find them confusing from time to time. – EXIT_FAILURE Nov 13 '17 at 13:34
  • @EXIT_FAILURE: ah, it uses `va_args`. See https://stackoverflow.com/questions/41400/how-to-wrap-a-function-with-variable-length-arguments – Vittorio Romeo Nov 13 '17 at 13:36