我知道我可以这样做来区分右值函数名和左值函数指针:
template <typename RET_TYPE, typename...ARGs>
void takeFunction(RET_TYPE(& function)(ARGs...))
{
cout << "RValue function" << endl;
}
template <typename RET_TYPE, typename...ARGs>
void takeFunction(RET_TYPE(*& function)(ARGs...))
{
cout << "LValue function" << endl;
}
void function()
{
}
void testFn()
{
void(*f)() = function;
takeFunction(function);
takeFunction(f);
}
我希望对会员职能也这样做。但是,它似乎没有翻译:
struct S;
void takeMemberFunction(void(S::&function)()) // error C2589: '&' : illegal token on right side of '::'
{
cout << "RValue member function" << endl;
}
void takeMemberFunction(void(S::*&function)())
{
cout << "LValue member function" << endl;
}
struct S
{
void memberFunction()
{
}
};
void testMemberFn()
{
void(S::*mf)() = &S::memberFunction;
takeMemberFunction(S::memberFunction);
takeMemberFunction(mf);
}
为什么?
我知道的另一种方法是为常规功能执行此操作:
void takeFunction(void(*&& function)())
{
cout << "RValue function" << endl;
}
void takeFunction(void(*& function)())
{
cout << "LValue function" << endl;
}
void function()
{
}
void testFn()
{
void(*f)() = function;
takeFunction(&function);
takeFunction(f);
}
哪个会转换为成员函数:
struct S;
void takeMemberFunction(void(S::*&&function)())
{
cout << "RValue member function" << endl;
}
void takeMemberFunction(void(S::*&function)())
{
cout << "LValue member function" << endl;
}
struct S
{
void memberFunction()
{
}
};
void testMemberFn()
{
void(S::*mf)() = &S::memberFunction;
takeMemberFunction(&S::memberFunction); // error C2664: 'void takeMemberFunction(void (__thiscall S::* &)(void))' : cannot convert argument 1 from 'void (__thiscall S::* )(void)' to 'void (__thiscall S::* &)(void)'
takeMemberFunction(mf);
}
但我想知道我的第一个没有翻译的例子的差异。
答案 0 :(得分:4)
我猜这是一个Visual C ++错误,如下面的代码(基本上你在你的问题中有什么){g}和clang上的compiles for me,我认为没有理由不期望它: / p>
struct S;
void bar(void (S::*& f)() ) {
std::cout << "lvalue" << std::endl;
}
void bar(void (S::*&& p)() ) {
std::cout << "rvalue" << std::endl;
}
struct S {
void foo() { }
};
int main() {
void (S::*f)();
bar(f); // prints lvalue
bar(&S::foo); // prints rvalue
}
有关问题的其他部分,请参阅Why doesn't reference-to-member exist in C++?。