简体   繁体   中英

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

Given

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

I can create a member function pointer like this:

typedef int (A::*PFN_FOO)(double, std::string&) const;

Easy enough, except that PFN_FOO needs to be updated if A::foo 's signature changes. Since C++11 introduces decltype , could it be used to automatically deduce the signature and create the typedef?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM