可以使用C++ 11 decltype为现有函数的函数指针创建typedef吗?

Dan*_*ger 30 c++ decltype c++11

特定

struct A { 
    int foo(double a, std::string& b) const;
};
Run Code Online (Sandbox Code Playgroud)

我可以像这样创建一个成员函数指针:

typedef int (A::*PFN_FOO)(double, std::string&) const;
Run Code Online (Sandbox Code Playgroud)

很容易,但PFN_FOO如果A::foo签名发生变化则需要更新.自C++ 11引入以来decltype,它是否可以用于自动推导签名并创建typedef?

Ros*_*ost 45

当然是:

typedef decltype(&A::foo) PFN_FOO;

您还可以通过using关键字定义类型别名(感谢Matthieu M.):

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

  • 您可以一直使用C++ 11:`使用PFN_FOO = decltype(&A :: foo);` (4认同)
  • +1回答,但希望我能给-1打30秒!:p (3认同)

Mat*_* M. 19

一个问题:如果此变量是明确的,您可能只推导出变量的类型.

函数的主要问题是重载意味着它们的名称不足以识别它们.因此,如果使用decltype失败,你应该引入fooin 的重载A.

struct A {
    void foo() const;
    void foo(int) const;
};

using PFN_FOO = decltype(A::foo);
Run Code Online (Sandbox Code Playgroud)
source.cpp:6:36: error: decltype cannot resolve address of overloaded function
Run Code Online (Sandbox Code Playgroud)

不确定你会获得多少......

另一方面,您实际上可以使用别名并检查别名是否正确:

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!");
Run Code Online (Sandbox Code Playgroud)

注意:不确定这是最好的测试方法,基本上你需要的只是static_cast部分,我只想隐藏一条错误信息.你可能需要像SFINAE这样的东西来获得更好的信息.