指向函数成员的指针:`R(* C :: *)(Args ...)`是什么意思?

时间:2015-12-02 05:04:07

标签: c++ c++11 member-function-pointers member-functions

请考虑以下代码:

template <class>
struct test: std::integral_constant<int, 0> {};
template<class R, class C, class... Args>
struct test<R(C::*)(Args...)>: std::integral_constant<int, 1> {};
template<class R, class C, class... Args>
struct test<R(*C::*)(Args...)>: std::integral_constant<int, 2> {};
template<class R, class C, class... Args>
struct test<R(**C::*)(Args...)>: std::integral_constant<int, 3> {};
template<class R, class C, class... Args>
struct test<R(C::**)(Args...)>: std::integral_constant<int, 4> {};
template<class R, class C, class... Args>
struct test<R(C::***)(Args...)>: std::integral_constant<int, 5> {};

我完全不知道(*C::*)(**C::*)(C::**)(C::***)是什么意思。我想要test<decltype(f)> value等于2345的示例。另外,在这种情况下,f的语法如何调用成员函数?

1 个答案:

答案 0 :(得分:18)

考虑this example

struct s {
    void test1();
    void(*test2)();
    void(**test3)();
};

int main() {
    static_assert(test<decltype(&s::test1)>::value == 1);   
    static_assert(test<decltype(&s::test2)>::value == 2);   
    static_assert(test<decltype(&s::test3)>::value == 3);   

    auto test4 = &s::test1;
    static_assert(test<decltype(&test4)>::value == 4);   

    auto test5 = &test4;
    static_assert(test<decltype(&test5)>::value == 5);   
}

以下是类型:

R(C::*)(Args...) - 指向成员函数的指针 R(*C::*)(Args...) - 指向作为函数指针的数据成员的指针 R(**C::*)(Args...) - 指向数据成员的指针,该数据成员是指向函数指针的指针 R(C::**)(Args...) - 指向成员函数指针的指针 R(C::***)(Args...) - 指向指向成员函数的指针的指针。

要调用这些内容,请考虑slightly modified example

struct s {
    void test1() {std::cout << "test1\n";}
    void(*test2)() = [] {std::cout << "test2\n";};

    void(*test3Helper)() = [] {std::cout << "test3\n";};
    void(**test3)() = &test3Helper;

    void test4() {std::cout << "test4\n";}
    void test5() {std::cout << "test5\n";}
};

int main() {
    s obj;  

    auto test4 = &s::test4;

    auto test5Helper = &s::test5;
    auto test5 = &test5Helper;  

    (obj.*(&s::test1))();
    (*(obj.*(&s::test2)))(); // note that the dereference is unnecessary
    (**(obj.*(&s::test3)))(); // note that the second dereference is unnecessary
    (obj.**(&test4))();
    (obj.***(&test5))();
}

请注意,在每种情况下,如果您的变量具有相应&[s::]testN的值,则可以使用该变量替换(&[s::]testN)。另请注意,对于test2和test3,我取消引用直到获取函数而不是函数指针用于说明目的。