如何区分重载函数的左值和右值成员函数指针
How do I differentiate an lvalue and rvalue member function pointer for overloaded functions?
我知道我可以这样做来区分右值函数名称和左值函数指针:
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);
}
但我想知道我的第一个示例不翻译的差异。
我猜这是一个视觉C++错误,因为以下代码(基本上是您在问题中的内容)在 gcc 和 clang 上为我编译,我认为没有理由期望它不这样做:
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
}
有关问题的另一部分,请参阅为什么C++中不存在对成员的引用?。
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针