would prefer a cleaner was of doing it if possible.
From here
takes_a_function(pass_function(s));
^^^^^^^^^^^^^^^^^^
it looks like you want to pass a something callable(pass_function) to another function(takes_a_function), after binding the argument(string array). If so, you have better options in C++.
First use either std::vector<std::string> or std::array<std::string, 2>(if size is known) to store the strings. Secondly, the passing of callable to another function, by either of the following ways:
Using a lambda and
std::bind
Make takes_a_function as a template function and then after
binding with the argument pass the callable object(pass_function
as a lambda function) to it.
#include <vector> // std::vector
#include <functional> // std::bind
template<typename Callable>
void takes_a_function(const Callable &function)
{
function(); // direckt call
}
int main()
{
std::vector<std::string> s{ "hello", "World" };
auto pass_function = [](const std::vector<std::string> &args) { /*do something*/ };
takes_a_function(std::bind(pass_function, s));
return 0;
}
Using function pointer
If the function pointer is unavoidable, you need two arguments in
takes_a_function, one should be the function pointer and the other
should be the array of strings.
#include <vector> // std::vector
// convenience type
using fPtrType = void(*)(std::vector<std::string> const&);
void pass_function(const std::vector<std::string> &args) { /*do something*/ };
void takes_a_function(const fPtrType &function, const std::vector<std::string> &args)
{
function(args); // call with args
}
int main()
{
std::vector<std::string> s{ "hello", "World" };
takes_a_function(pass_function, s);
return 0;
}
pass_function(s)is of typevoidbecause you called the function. And then you tried to pass the return value.takes_a_functionis noop