gpt4 book ai didi

c++ - 成员函数的decltype

转载 作者:可可西里 更新时间:2023-11-01 16:04:37 25 4
gpt4 key购买 nike

class A {
int f(int x, int j) { return 2;}
decltype(f)* p;
};

给我错误:

error: decltype cannot resolve address of overloaded function

我不明白为什么这个错误甚至是在谈论重载函数。同样,我认为也许我需要使用作用域运算符来访问该函数:

class A {
int f(int x, int j) { return 2;}
decltype(A::f)* p;
};

这仍然给我一个错误,但描述更清晰:

error: invalid use of non-static member function 'int A::f(int, int)'

为什么不允许我使用 decltype 来查找成员函数的类型?或者,将成员函数设置为 static 可以消除两种情况下的错误。

最佳答案

你真正想要的是:

struct a {
int f(int x, int j) { return 2;}
decltype(&a::f) p;
};

Live demo

f你指的是一个成员函数。推导的类型是:

int(a::*)(int, int)

没有 &编译器假设您正在尝试调用该函数而不向其提供参数。也许 Clang 的错误消息对此更清楚:

error: call to non-static member function without an object argument
decltype(a::f) p;

如果你真的不想要指针类型你可以稍后申请std::remove_pointer_t来自 <type_traits> .

关于c++ - 成员函数的decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113740/

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