English 中文(简体)
C++绑定函数
原标题:C++ - binding function

我有一些(库API,因此无法更改函数原型)函数,其编写方式如下:

void FreeContext(Context c);

现在,在我执行的某个时刻,我有Context*local_Context变量,这也是不受更改的主题

我希望使用boost::bindFreeContext函数,但我需要从局部变量Context*中检索Context

如果我以以下方式编写代码,编译器会说这是“非法间接寻址”:

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

我设法通过以下方式解决了这个问题:

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

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

但这个解决方案对我来说似乎并不太好。关于如何使用*_1之类的东西来解决这个问题,有什么想法吗<也许写一个小lambda函数

最佳回答

您可以使用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
", 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;
}
问题回答

使用Boost.Lambda或Boost.Fenix在占位符上有一个有效的运算符*

您还可以将Context指针放置在带有自定义deleter的shared_ptr中:

#include <memory> // shared_ptr

typedef int Context;

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

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

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

但不确定这是否相关。祝你好运





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签