Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redefining a function with a template

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)
like image 209
EXIT_FAILURE Avatar asked Nov 24 '25 22:11

EXIT_FAILURE


2 Answers

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.

like image 181
mrks Avatar answered Nov 27 '25 12:11

mrks


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.

like image 42
Vittorio Romeo Avatar answered Nov 27 '25 14:11

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!