Can C++11 decltype be used to create a typedef for function pointer from an existing function?

前端 未结 2 1060
谎友^
谎友^ 2021-02-03 20:02

Given

struct A { 
    int foo(double a, std::string& b) const;
};

I can create a member function pointer like this:

typedef         


        
相关标签:
2条回答
  • 2021-02-03 20:37

    One issue: you may only deduce the type of a variable if this variable is unambiguous.

    The main issue with functions is that overloads mean that their names alone are insufficient to identify them. Therefore using decltype fails should you ever introduce an overload of foo in A.

    struct A {
        void foo() const;
        void foo(int) const;
    };
    
    using PFN_FOO = decltype(A::foo);
    
    source.cpp:6:36: error: decltype cannot resolve address of overloaded function
    

    Not sure you'll be gaining much thus...

    On the other hand, you can actually use an alias and check that alias is right:

    struct A {
        void foo() const;
        void foo(int) const;
    };
    
    using PFN_FOO = void (A::*)(int) const;
    
    static_assert(std::is_same<PFN_FOO, decltype(static_cast<PFN_FOO>(&A::foo))>::value,
         "Ooops, need to update signature of PFN_FOO!");
    

    Note: not sure this is the best way to test, basically all you need is the static_cast part, I just wanted to stash an error message alongside. You would probably need something like SFINAE to get better messages though.

    0 讨论(0)
  • 2021-02-03 20:51

    Yes, of course:

    typedef decltype(&A::foo) PFN_FOO;

    You can also define type alias via using keyword (Thanks to Matthieu M.):

    using PFN_FOO = decltype(&A::foo);

    0 讨论(0)
提交回复
热议问题