Question

I have some (library API, so I can't change the function prototype) function which is written the following way:

void FreeContext(Context c);

Now, at some moment of my execution I have Context* local_context; variable and this is also not a subject to change.

I wish to use boost::bind with FreeContext function, but I need to retrieve Context from local variable Context*.

If I write my code the following way, the compiler says it's "illegal indirection":

boost::bind(::FreeContext, *_1);

I managed to solve this problem the following way:

template <typename T> T retranslate_parameter(T* t) {
   return *t;
}

boost::bind(::FreeContext,
            boost::bind(retranslate_parameter<Context>, _1));

But this solution doesn't seem really good to me. Any ideas on how to solve this using something like *_1. Maybe writing a small lambda function?

Was it helpful?

Solution

You could use Boost.Lambda which have overloaded the * operator for _n.

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <algorithm>
#include <cstdio>

typedef int Context;

void FreeContext(Context c) {
    printf("%d\n", c);
}

int main() {
    using boost::lambda::bind;
    using boost::lambda::_1;

    Context x = 5;
    Context y = 6;
    Context* p[] = {&x, &y};

    std::for_each(p, p+2, bind(FreeContext, *_1));

    return 0;
}

OTHER TIPS

Use either Boost.Lambda or Boost.Phoenix to have a working operator* on a placeholder.

You can also place the Context pointer in a shared_ptr with a custom deleter:

#include <memory> // shared_ptr

typedef int Context;

void FreeContext(Context c)
{
   printf("%d\n", c);
}

int main()
{
   Context x = 5;
   Context* local_context = &x;

   std::shared_ptr<Context> context(local_context,
                                    [](Context* c) { FreeContext(*c); });
}

Not sure this is relevant though. Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top