Is there any way to rest set/array to method parameters? - c++

Currently I have a function:
void translate(std::string key, std::string& result, ...)
{
char buffer[1024];
va_list args;
va_start(args, result);
vsnprintf (buffer, sizeof(buffer), (loadedTranslations.find(key) != loadedTranslations.end() ? loadedTranslations[key] : "unknown").c_str(), args);
va_end(args);
result = buffer;
}
I'm getting some data in AMX plugin and I need to pass them into this function. Is there are any way to do this? In JavaScript I can do something like translate(a, b, ...rest) and it will work. Is there some ways to implement same result in C++? The problem is the data isn't one type: there can be integers, floats and strings. So using std::forward (if I correctly understood its use-case) not possible.

Try:
template <typename ... Args>
void translate(std::string key, std::string& result, Args&& ... args)
{
// your code
}
and wherever you need to forward, for eg. to a function foo: foo(std::forward<Args>(args)...)
I'll suggest reading more about variadic template and perfect forwarding.

Related

Calling variadic printf() from variadic C++ function

There are 2 ways of doing it:
template<class arg, class... args>
void test1(arg format, args... va)
{
printf(format, va...);
}
void test2(const char* format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
test1("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);
test2("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);
Both function do the same, what are the pros and cons of each approach?
When I google for "variadic functions in C++" I get the C style stdarg answer first.
Then "see variadic templates...".
I've read about both, and for the first glance the templated function seems neater. Shorter code, much more readable. But are there any catches? Which one is faster?

Is it possible to pass variadic template parameters to va_list?

A mirroring question of Is it possible to pass va list to variadic template
In my project for testing, there is a function:
void Func(LPCSTR format, ...) {
va_list args;
va_start(args, format);
char buffer[256];
vsprintf_s(buffer, 256, format, args);
printf("%s\n", buffer);
va_end(args);
}
And I write a template function:
template<typename... Args>
void FuncTemp(LPCSTR format, Args... args) {
Func(format, args...); //#1
}
Is the call for Func in line #1 right? I have tested my program, and it seemed to produce the correct results. Are there problems or pitfalls writing like this way?
The logic behind this:
I want to realize a log writing class which can decide to write logs to local positions or submitte to servers:
Class LogWriting{
public:
...
LogTypes mLogType;
void WriteLogs(...){
switch (mlogType) {
case(LogTypes::local): {
// need to call <void LogLocal(LPCSTR format, ...)> here
// which CANNOT be changed.
break;
}
case(LogTypes::online): {
// need to call
/* template<typename... Args>
void LogOnline(LPCSTR format, Args... args)
{
std::string strFormat = std::string(format);
std::string logMessage = fmt::sprintf(strFormat, args...);
reportLog(logMessage);
}
*/
// which CANNOT be changed.
break;
}
...
}
};
Because I cannot change the parameters' types of LogLocal() and LogOnline()(one is va_list and another is variadic template), I decided to set WriteLogs() as a variadic function template to suit these two functions:
template<typename... Args>
void WriteLogs(LPCSTR format, Args... args)

Pass param packed args into a std::queue to call with a different function later

I asked a similar question earlier without realizing that that wasn't quite specific enough.
So I have this function that has to take in all the arguments of a print function, with the ... and all, and then put it into a queue that will call the actual print function later.
Something like:
std::queue<SOMETHING> queue;
template <typename... Params>
void printLater(int a, int b, char* fmt, Params ...args) {
queue.push(args);
}
template <typename... Params>
void print(int a, int b, char* fmt, Param ...args) {
//whatever
}
void actuallyPrint() {
//whatever
print(queue.pop());
}
Context: I'm working with a piece of hardware that can only handle requests every 50ms or else they're ignored. My goal is to create a wrapper that will automatically add the delays if I send it a bunch at once.
My fallback if I cant do this, although I'd rather do this is just sprintf (or C++ equivalent) into a string only store the string in the queue and call print() without all the args.
Something like this perhaps:
std::queue<std::function<void()>> queue;
template <typename... Params>
void printLater(int a, int b, char* fmt, Params ...args) {
queue.push([=](){ print(a, b, fmt, args...); } );
}
void actuallyPrint() {
queue.front()();
queue.pop();
}

C++ - vsprintf_s and std::string?

I have a logging function that uses '...' parameters and creates the final output string with vsprintf_s
it works fine except that I always have to use c_str() to print strings
at first I thought it was not a problem, but it's a pain to add all these .c_str() after each string variables, while I keep forgetting them
I though maybe a C++ guru could enlight me on this issue, is there a way to have my logging function take care of this by itself ?
void Logger::print(const std::string fmt, ...)
{
va_list args;
int len;
char * buffer;
va_start(args, fmt);
len = _vscprintf(fmt.c_str(), args)+1;
buffer = (char*)malloc(len * sizeof(char));
vsprintf_s(buffer, len, fmt.c_str(), args);
va_end(args);
std::cout << buffer << std::endl;
free(buffer);
}
thanks
You can add two variadic wrapper function templates like this:
#include <type_traits>
template <class Arg>
decltype(auto) prepare(const Arg& arg)
{
if constexpr (std::is_same_v<Arg, std::string>)
return arg.c_str();
else
return arg;
}
template <class ...Args>
void printWrapper(Args&&... args)
{
Log::print(prepare(std::forward<Args>(args))...);
}
and invoke printWrapper instead of the original member function. Note that I assumed Log::print to be static member function here. If that't not the case, you need adjust it. This should work now:
const std::string hello("hello");
printWrapper("%d %s %s", 42, hello, "world");
Note that C++17 is required for this to compile.

To invoke a variadic function with unamed arguments of another variadic function

I have two variadic function as foo(format, ...) and bar(format, ...). I want to implement function foo so that it can invoke bar with the same list of arguments it has. That is,
foo(format...)
{
...
bar(format, ...);
}
For instance, invoking foo("(ii)", 1, 2) will invoke bar with same arguments bar("(ii)", 1, 2). How should this foo function be implemented?
PS: function bar is from a legacy library which I cant change its interface.
Can't be done, as long as all you have is a bunch if functions with ... arguments.
You have to plan ahead for things like that and implement each variadic fuinction in two-staged fashion
void vfoo(format, va_list *args) {
/* Process `*args` */
}
void foo(format, ...) {
va_list args;
va_start(args, format);
vfoo(format, &args);
va_end(args);
}
Once you have each of your variadic functions implemented through a pair of va_list * function and ... function, you can delegate the calls using the va_list * versions of the functions
void vfoo(format, va_list *args) {
...
vbar(format, args);
...
}
GCC can construct function calls at runtime.
foo() {
void *args = __builtin_apply_args();
void *ret = __builtin_apply(bar, args, ???);
__builtin_return(ret);
}
??? is the amount of stack space the arguments take up, which is not necessarily trivial to compute: you will need to understand what the arguments are and architecture-specific details on how they are passed.
Other GCC extensions allow further trickery with macros and inline functions.
Short answer - you cannot. Make bar take a va_list. If you're willing to lock this down to one specific compiler, you could probably do it with inline assembly, but with standard C or C++ it's not possible.
You should, as a general rule, always implement your vararg functions in terms of va_list and then make a wrapper ellipsis function calling the real va_list function.
This works in C++:
#include <iostream>
template<typename Format>
void meheer(const Format& format) {
std::cout << format << std::endl;;
}
template<typename Format, typename Elt, typename ... Args>
void meheer(const Format& format, const Elt & e, const Args&... args) {
std::cout << format << e;
meheer(format, args...);
}
template<typename Format, typename ... Args>
void ohai(const Format& format, const Args&... args) {
meheer(format, args...);
}
int main(int argc, char ** argv) {
ohai(1,2,3);
return EXIT_SUCCESS;
}
Output:
12131
Of course, this is C++0x specific, but it works in my not-super-recent version of gcc. See also: http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates
Update Added full-length example.