C++:std::bind() 如何"知道"模板参数是指静态函数还是成员函数?

c++ : how does std::bind() 'know' whether the template args refer to a static function or member function?

本文关键字:静态函数 成员 函数 参数 bind std 如何 C++ 知道      更新时间:2023-10-16

使用 bind() 我可以做到这两点:

void f(int a) { }
class C {
public:
    void f (int a) { }
};
int main()
{
    auto f1 = std::bind (f,3);
    f1();
    C myC;
    auto f2 = std::bind (&C::f, &myC, 3);
    f2();
}

大概在下面,f1()以某种方式被翻译成f(3),f2()被翻译成(&myC)->f(3)。我不太关心"3"参数的绑定,但我想了解 bind() 如何自动知道 f1 应该只是一个直接的函数调用,而 f2 应该是一个对象的成员调用。在编译时,用于检查第一个参数的"风味"是什么技术是什么?我想在我自己的程序中利用这种技术。

一种简单、打包的方法是使用

std::is_member_function_pointer<F>::value

其中F是第一个参数的类型,可能删除了潜在的引用和 CV 限定。