【发布时间】:2015-04-18 16:39:30
【问题描述】:
我知道我可以这样做来区分右值函数名称和左值函数指针:
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);
}
但我想知道我的第一个示例没有翻译的差异。
【问题讨论】:
-
“这不起作用” :(
-
@LightningRacisinObrit:嗯?不是有用的评论。
-
实际上,如果您将其阅读为“'这不起作用'不是有用的问题描述”。希望是在不解释显而易见的情况下推动您改进它!
-
函数名的右值是从什么时候开始的?
-
如果您真的阅读了 [basic.lval] 引用,您会看到“左值 [...] 指定函数或对象”。此外,[conv.fptr]/p1:“函数类型 T 的左值可以转换为“指向 T 的指针”类型的纯右值。结果是指向函数的指针。” [expr.prim.general]/p8:“一个 identifier 是一个 id-expression,前提是它已被适当地声明(第 7 条)。[...] 类型"
标签: c++ c++11 visual-c++