0

Welcome, this is very rare use-case question.
So, here is what I'm trying to do - lets say I have a variadic template function which takes T ...args and a function type FuncT funcName, so here is what we have so far:

template<typename FuncT, typename ...T>
void myFunction(FuncT (*funcName), T ...args);

Now, I want to store my function at void (*)() (this store functions). This works just fine.

std::deque<void (*)()> functions;
func = functions.front();
func(std::forward<T>(args)...); //args is vardict template argument

Now, I can just pass a function to my function as in:

template<typename FuncT, typename T>

int sharedArgument;

void setArg(int x){
  sharedArgument = x;
}
template<typename FuncT>
void myFunction(FuncT funcName){
  funcName(sharedArgument);
}

void function(int i){
  std::cout << i;
}

int main(){
  setArg(5);
  myFunction(function);
}

Now, I know this is unnecesary, but i want to present a more complicated problem that im having trouble with.

When i want to store arguemnts, I will probably use std::tuple, its design to store arguments, but
Main question is:
How do i store variable amount of arguments in tuple and then perfectly forward them as normal arguments to some function, so that function receiving

function(std::tupleArgumentsHere...);

will read it as

function(5, 42, "yes", 3.14);

I will use this to store arguments and pass them to std::thread.


Thank you, Cheers.

1
  • soo std::bind? Commented Feb 1, 2021 at 17:27

2 Answers 2

1

Use std::apply. It is new in . If you cannot, write your own.

In , make an index sequence the same length as your tuple. Then func(std::get<Is>(std::forward<Tup>(tup))...).

In do the same thing but write your own index sequence.

Sign up to request clarification or add additional context in comments.

3 Comments

Tuple is variable length, thats the problem
@arma apply works with variable length tuples. So long as you know the function type and the tuple type, just call apply with the actual correctly typed values.
Thanks, would be glad to know if there is c++11 way that works like apply, but still marking as the answear, thank you!
0

std::bind stores the function and the arguments together. It returns a callable object encapsulating a copy of the argument values.

You can also use its "placeholder" facility in case there are additional arguments to add after calling queue.front().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.