C ++ - binding function

I have some (API library, so I can not change the prototype function), which is written as follows:

void FreeContext(Context c);

Now, at some point in my execution, I have a variable Context* local_context;, and that too cannot be changed.

I want to use boost::bindwith a function FreeContext, but I need to get Contextfrom a local variable Context*.

If I write my code as follows, the compiler says that this is “illegal indirection”:

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

I managed to solve this problem as follows:

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

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

But this decision seems to me not very good. Any ideas on how to solve this using something like *_1. Maybe write a little lambda function?

+3
3

Boost.Lambda, * _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;
}
+4

Boost.Lambda Boost.Phoenix operator* .

+2

You can also put the pointer Contextin shared_ptrwith user deletion:

#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 if this is relevant. Good luck

+1
source

Source: https://habr.com/ru/post/1769512/


All Articles