c++ - 类成员的 std::mem_fn 不会编译

标签 c++ qt c++11

我正在使用 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 a std::mem_fn.

在所有情况下,提供给可调用包装器的第一个(或唯一)参数是指向类实例的指针或引用。

first_argument_type T* if pm is a pointer to member function taking one argument

这些要求类似于旧的 std::mem_funstd::mem_fun_ref以及它们的使用方式。

关于c++ - 类成员的 std::mem_fn 不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31422385/

相关文章:

c++ - MFC VC++ 自定义复选框图像

添加或删除模型中的项目时,Qt QML 通知 ListView

qt - 纬度/经度 Qt4 小部件?

c++11,为什么这个为 vector <int> 定义的 unordered_map 不起作用?

c++ - 使用高斯核的一维卷积

c++ - 在 SDL 中打印键的名称

c# - 混合程序集未发现 native DLL

qt - 当应用程序被要求退出时允许用户交互

c++ - C++ 标准对使用 noexcept 覆盖 throw() 函数有何规定?

c++ - 在 Visual Studio 2013 上编译旧的 C++ 代码