【发布时间】:2016-05-12 19:10:56
【问题描述】:
考虑这段代码:
#include <iostream>
#include <functional>
struct B {
template <class C, class M, class T>
void call1(C (M::*member)(), T *instance) {
std::function<void()> fp = std::bind(member, instance);
fp();
}
template <class C, class M, class T>
void call2(C (M::*member), T *instance) {
std::function<void()> fp = std::bind(member, instance);
fp();
}
void foo() {
call1(&B::func, this); // works
call2(&B::func, this); // works
call1(&B::func2, this); // Error: no matching member function for call to 'call2'
call2(&B::func2, this); // works
}
void func() {
std::cout << "func\n";
}
void func2() const volatile {
std::cout << "func2\n";
}
};
int main() {
B{}.foo();
}
似乎更高版本不接受带有额外 cv 限定符的函数。
指定像这样C (M::*member)()和像这样C (M::*member)这样的函数成员指针有什么区别?
【问题讨论】:
-
我什至不知道
C (M::*member)是有效的语法... -
重点是
call1不会接受带有 cv-qualifiers 的函数,而call2允许。 -
不相关,但为什么要麻烦使用
std::bind而不是直接调用成员函数呢?(instance->*member)(); -
@Snps 抱歉,那是我的错误。我已经修好了。
-
@VioletGiraffe 在这种情况下括号是多余的。
标签: c++ function pointers c++11