从“内部”开始const
:
using void_function = void();
void (*p1)() = nullptr; // similar to `void_function* p1 = nullptr;`
void (* const p2)() = nullptr; // similar to `void_function* const p2 = nullptr;`
p2
是constant
而是p1
可变的。
移动const
时,如下:
const void_function* p3 = nullptr; // or void_function const* p3; // -> const has no effect
void (const* p4)() = nullptr; // Invalid syntax
没有“const
函数”与“可变函数”。
现在,查看函数返回类型:
类型void ()
(函数返回void
)和const void ()
(函数返回const void
!?)是不同的。
即使const void
没有真正的意义,它也是一个有效的类型。
const
从函数返回对象以禁止“直接”修改对象可能是有意义的:
const std::string make_const_string();
make_const_string().push_back('*'); // Doesn't work
std::string s = make_const_string(); // OK, create mutable copy.
所以要修复你的代码:
struct A {
static void a() {}
};
void b(void const (* const callback)()) {}
int main() {
b(&A::a); // No matching function for call to 'b'
}
您必须使&A::a
matchb
的参数类型:
static const void a() {}
void b(void (*const callback)())
我建议第二个const void
没有真正意义。