gpt4 book ai didi

c++ - 获取 const 方法的地址

转载 作者:行者123 更新时间:2023-12-01 14:36:34 27 4
gpt4 key购买 nike

我希望能够形成一个只知道类本身和方法名称的成员指针类型。不幸的是,我无法在我的类中使用 const 和非常量方法变体。

示例代码片段:

struct A
{
void method() {}
void method() const {}
};

int main()
{
decltype(&A::method) _;
}

我也尝试过以下方法,但也没有太大成功:

decltype(&(std::declval<const A>().method)) _;

这两种方法都失败了,因为 decltype 由于歧义无法解决这个问题:

'decltype cannot resolve address of overloaded function'

我怎样才能通过其他方式实现这一点?

最佳答案

你可以这样做:

struct A
{
void method() {
cout << "Non const\n";
}
void method() const {
cout << "const function\n";
}
};

int main()
{
typedef void (A::*method_const)() const;
method_const a = &A::method; //address of const method

typedef void (A::*method_nonconst)();
method_nonconst b = &A::method; //address of non const method

A var;
std::invoke(a, var);
std::invoke(b, var);
}

如果你想使用decltype()要实现相同的目的,您首先必须使用 static_cast<> 手动选择您想要的功能:

int main()
{
//const
decltype( static_cast <void (A::*)() const> (&A::method) ) a;
//non const
decltype( static_cast <void (A::*)()> (&A::method) ) b;

a = &A::method;
b = &A::method;

A var;
std::invoke(a, var);
std::invoke(b, var);
}

Live on Coliru

关于c++ - 获取 const 方法的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63338608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com