非静态成员函数reinterpre_cast失败
non-static member function reinterpret_cast failed
代码:
#include <iostream>
using namespace std;
struct item
{
int f1() {}
double f2() {}
static int g1() {}
static double g2() {}
void f0();
};
void item::f0()
{
auto c1 = reinterpret_cast<decltype(f2)>(f1);
auto c2 = reinterpret_cast<decltype(g2)>(g1);
auto c3 = reinterpret_cast<decltype(&f2)>(f1);
auto c4 = reinterpret_cast<decltype(&g2)>(g1);
}
int main()
{
cout << "Hello world!" << endl;
return 0;
}
错误消息:
main.cpp|17|error: invalid use of non-static member function|
main.cpp|18|error: invalid cast from type ‘int (*)()’ to type ‘double()’|
main.cpp|20|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&item::f2’ [-fpermissive]|
main.cpp|20|error: invalid use of member function (did you forget the ‘()’ ?)
我的问题:作为参数传递的成员函数将自动转换为指针,所以我尝试将参数强制转换为指针但仍然失败。我不明白为什么非静态成员函数根本不起作用情况
您需要强制转换
f1
的返回值,而不是f1
。用途:
auto c1 = reinterpret_cast<decltype(f2())>(f1());
^^ Call the function
对其他行进行类似的更改。
我误解了你想做的事情。以下应该有效:
auto c1 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
auto c2 = reinterpret_cast<decltype(&g2)>(g1);
auto c3 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
auto c4 = reinterpret_cast<decltype(&g1)>(g2);
f1
是一个非static
成员函数。您可以使用f1()
来调用它。但是,如果没有函数调用语法,非静态成员函数不会自动衰减为成员函数指针。要获得struct
的成员函数指针,您需要使用&item::f1
。
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 如何理解C++标准N3337中的expr.const.cast子句8
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- C++Cast运算符过载
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- LibGit2 SSH身份验证失败
- 如何让LLDB在成功时退出,在失败时等待
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 编译错误:C/ c++中cast void *失败