Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

C++ Function with variable number and types of arguments as argument of another function

I would like to create function calling another function and printing its arguments.
It should be compatible with many functions (returning the same result) with many combinations of variables of arguments.

I would like to have something like this:

int fun1(){}
int fun2(int i){}
int fun3(std::string s, int i){}

void execute_and_print(std::function f, ...)
{
///code
}

int main()
{
execute_and_print(&fun1);
execute_and_print(&fun2, 3);
execute_and_print(&fun3,"ff",4);
}

It could print:

executed function with arguments:
executed function with arguments: 3
executed function with arguments: ff, 4

Is it even possible in C++?

question from:https://stackoverflow.com/questions/65886397/c-function-with-variable-number-and-types-of-arguments-as-argument-of-another

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is not foolproof, but any possible errors will be caught at compile time (ie. the code will not compile). It should work file, as long as the provided parameters match those of the called function, and a matching << operator exists for each parameter.

template<class Fn, class...Args>
void execute_and_print(Fn fn, Args...args) {
    int f[sizeof...(Args)] = { (std::cout << args << ", ", 0)... };
    fn(args...);
}

Refer to https://en.cppreference.com/w/cpp/language/parameter_pack. The sizeof... command is actually the number of elements, not their combined size.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...