我正在使用 C++11 和 MSVC2013 尝试在我的类中使用函数指针来拥有自己的成员函数。
class MyClass
{
public:
// ...
QColor Colorize(double dValue) const;
private:
bool m_bUseColor1;
QColor Color1(double dValue) const;
QColor Color2(double dValue) const;
};
实现
QColor MyClass::Colorize(double dValue) const
{
auto colorize_func = m_bUseColor1 ? std::mem_fn(&MyClass::Color1) : std::mem_fn(&MyClass::Color2);
QColor myColor = colorize_func(23.3);// FAILS TO COMPILE
}
这会产生以下错误:
Error 102 error C2100: illegal indirection C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap 311 Error 103 error C2296: '.*' : illegal, left operand has type 'double' C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap 311
知道这里出了什么问题吗?我遵循了 cppreference mem_fn
的语法但显然有错误。
最佳答案
colorize_func(23.3)
的使用需要类MyClass
的实例才能编译运行。不仅仅是函数的参数。
例如:
MyClass mc;
// ....
colorize_func(mc, 23.3);
由于成员函数中已经使用了colorize_func
,所以您也可以使用this
。
QColor myColor = colorize_func(this, 23.3);
应该这样做。
反正代码都是member的一部分,也可以把代码简化为;
QColor MyClass::Colorize(double dValue) const
{
return (m_bUseColor ? Color1(dValue) : Color2(dValue));
}
关于 std::mem_fn
的注释它的用途(引自 cppreference.com);
Function template
std::mem_fn
generates wrapper objects for pointers to members, which can store, copy, and invoke a pointer to member. Both references and pointers (including smart pointers) to an object can be used when invoking astd::mem_fn
.
在所有情况下,提供给可调用包装器的第一个(或唯一)参数是指向类实例的指针或引用。
first_argument_type
T*
ifpm
is a pointer to member function taking one argument
这些要求类似于旧的 std::mem_fun
和 std::mem_fun_ref
以及它们的使用方式。
关于c++ - 类成员的 std::mem_fn 不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31422385/