gpt4 book ai didi

c++ - 如何区分重载函数的左值和右值成员函数指针?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:42 25 4
gpt4 key购买 nike

我知道我可以这样做来区分右值函数名和左值函数指针:

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);
}

但我想知道我的第一个例子没有翻译的差异。

最佳答案

我猜这是一个 Visual C++ 错误,如下面的代码(基本上是您问题中的内容)compiles for me在 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
}

关于您问题的其他部分,请参阅 Why doesn't reference-to-member exist in C++? .

关于c++ - 如何区分重载函数的左值和右值成员函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com