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

前端 未结 2 1062
谎友^
谎友^ 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(&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.

提交回复
热议问题