我有2个班级:
MeshInput
和VoxelGrid
。 VoxelGrid
具有成员 sdf
,它是一个函数指针。现在我想将另一个类的非静态函数分配给sdf
。我无法更改其中任何一个的签名,因为 sdf
有时也指向 MeshInput
之外的函数。我该怎么做?
代码如下:
class VoxelGrid {
private:
double (*sdf)(tg::pos3 const&);
}
class MeshInput {
public:
double sdfFromMesh(tg::pos3 const& point);
}
根据我的理解,问题是,当使用函数指针调用函数时,没有像从对象调用它时那样的隐式
this*
指针(A.sdfFromMesh()
)。但我不知道如何解决这个问题。
您可以使用
std::function
配合std::bind
。
std::bind
可以指定要保留的特定目标函数及其所属位置。例如:
struct Foo
{
double get(tg::pos3 const&) { return 0; }
};
然后你可以将
get
绑定到你的变量,如下所示:
std::function<double ( tg::pos3 const& )> sdf = std::bind(&Foo::get, &YourFooObj, std::placeholders::_1)
请参阅 std::bind 和 std::function 了解更多详细信息。