[英]How can I overload operator= for lambda assignments?
我試圖將一個函數插入到映射中,但是我想先檢查一下,所以我想重載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; };
^
聽起來您需要的是代理類 。 問題是,當您從on()
返回std::function<..>&
,最終會得到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()
將編譯並執行您期望的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.