声明类成员函数的命名类型

问题描述 投票:0回答:1

我的类有一组具有完全相同签名的成员函数。

我需要显式声明这些成员方法的命名类型,以便定义可以使用这些方法之一进行赋值的变量/参数。

像这样:

class Point_t {
private:
    int X;
    int Y;
public:
    int getX();
    int getY();
};

// This is only to define a variable, not a type name
int (Point_t::*var_name)() = &Point_t::getX;

但它只是定义一个变量,而不是声明类型名称。

此外,这是C风格的,我认为它在我的C++代码中非常难看。

有现代 C++ 风格吗?

我希望它看起来像:

using method_type = Point_t::*;

谢谢!

c++ typedef using pointer-to-member member-functions
1个回答
0
投票

最简单的方法是使用

decltype
说明符,其中:

检查实体的声明类型或表达式的类型和值类别。

在你的情况下是:

using method_type = decltype(&Point_t::getX);

如果您出于某种原因想避免

decltype
,您也可以在不使用它的情况下执行以下操作:

using method_type = int (Point_t::*)();
© www.soinside.com 2019 - 2024. All rights reserved.