1

External API requires function void foobar(void (*func)(void)), and I can not change it. How I can pass into this function another variables?

foobar([](){});

This code works fine.

foobar([this](){});

But this - not. Why?

dyp
  • 38,334
  • 13
  • 112
  • 177
nkt
  • 75
  • 1
  • 7
  • 3
    Because `[this](){}` cannot be expressed as an ordinary function, it has state. Lambdas are no magic. – dyp Jun 08 '14 at 21:28
  • I understand that. So how I can do it? Maybe some std::bind/std::function magic? – nkt Jun 08 '14 at 21:32
  • 1
    You have to insert state into the function. For example, using `thread_local` storage, static storage, global storage, ... The interface of `foobar` simply is not flexible enough to support stateful function objects itself. – dyp Jun 08 '14 at 21:33
  • Anyway, as it stands, this is a duplicate question, [this Q/A](http://stackoverflow.com/a/7852154/420683) should be close enough to this question. – dyp Jun 08 '14 at 21:34
  • 1
    @Csq I don't quite like my superpowers, but well, if you agree... (edit: huh? oh, it wasn't *originally* tagged [c++])@ nkt You can ask a new, more specific question if you like. But in this general form, I think it already has been asked many times on StackOverflow. – dyp Jun 08 '14 at 21:42
  • The problem is that the external API is badly designed. Any decent interface would at least allow for a function plus context pointer. – Alan Stokes Jun 08 '14 at 21:43
  • [n3574](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3574.html) proposes adding similar functionality to the standard, but it isn't even near acceptance... Implementing it yourself involves runtime code generation. – Mankarse Jun 08 '14 at 21:46

0 Answers0