我试图将一个函数插入到映射中,但是我想先检查一下,所以我想重载std :: function的赋值操作,这可能吗?
我尝试重载赋值操作,因此,如果分配了非预期的内容,则赋值运算符函数应将其包装在预期的函数中并返回它。

#include <iostream>
#include <map>
#include <functional>

class MyClass{
    public:
    std::map<int, std::map<int, std::function<void(int,int)>>> events;
    std::function<void(int,int)>& on(int type, int id){ return events[type][id]; };
    template<typename T> std::function<void(int,int)>& operator= (T&& fn){
        std::wcout << L"assigning correct function\n";
        return [&](int x, int y){
            if(typeid(fn)==typeid(std::function<void(int,std::wstring)>)) fn(x, L"two");
        };
    }
};

int main(int argc, char **argv)
{
    MyClass obj;
    obj.on(1,2) = [](int x, int y){ std::wcout << L"int " << x << L" " << y << std::endl; };  //this works but it's not calling the overload operator
    obj.on(1,2) = [](int x, std::wstring y){ std::wcout << L"string " << x << L" " << y << std::endl; }; //I need this to work too
    obj.events[1][2](2,3);
    return 0;
}


输出:

test.cpp:23:14: error: no match for 'operator=' (operand types are 'std::function<void(int, int)>' and 'main(int, char**)::<lambda(int, std::__cxx11::wstring)>')
obj.on(1,2) = [](int x, std::wstring y){ std::wcout << L"string " << x << L" " << y << std::endl; };
         ^

最佳答案

听起来您需要的是一个代理类。问题是,当您从std::function<..>&返回on()时,最终会得到std::function。您不能覆盖该类的operator=,这是我认为您正在尝试执行的操作。相反,您将覆盖MyClass::operator=-这是您从未真正调用过的函数。

而是返回一个您可以控制其分配的代理。像这样:

struct Proxy {
    std::function<void(int, int)>& f;
};

Proxy on(int type, int id){ return {events[type][id]}; };


然后我们可以为Proxy::operator=提供特殊的重载。 “有效,正确的类型”情况:

template <typename F,
          std::enable_if_t<std::is_assignable<std::function<void(int, int)>&, F&&>::value>* = nullptr>
Proxy& operator=(F&& func) {
    f = std::forward<F>(func);
    return *this;
}


wstring情况:

template <typename F,
          std::enable_if_t<std::is_assignable<std::function<void(int, std::wstring)>&, F&&>::value>* = nullptr>
Proxy& operator=(F&& func) {
    std::wcout << L"assigning correct function\n";
    f = [func = std::forward<F>(func)](int x, int ) {
        func(x, L"two");
    };
    return *this;
}


这样,您原始的main()将编译并执行您期望的操作。

关于c++ - 如何为lambda分配重载operator =?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32639087/

10-11 04:07
查看更多