我知道以下方法可以区分右值函数名和左值函数指针:
但我想知道第一个例子翻译时的差异。
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);
}
但我想知道第一个例子翻译时的差异。