【问题标题】:Pointer to function members: what does `R(*C::*)(Args...)` mean?指向函数成员的指针:`R(*C::*)(Args...)` 是什么意思?
【发布时间】:2016-03-06 06:06:37
【问题描述】:

考虑以下代码:

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&lt;decltype(f)&gt; 的示例,其value 将等于2345。另外,在这种情况下,调用成员函数的f 的语法如何?

【问题讨论】:

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


    【解决方案1】:

    考虑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))();
    }
    

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

    【讨论】:

    • 谢谢!你能举个例子,如果s有一个函数成员int f(int x) {return x;},而testN引用了它,那么在变量上执行testN的语法是什么?
    • @Vincent,我明白了。一秒钟。
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    相关资源
    最近更新 更多