如何重载lambda赋值的operator= ?
How can I overload operator= for lambda assignments?
我试图插入一个函数到一个映射,但我想先检查它,所以我想重载赋值操作std::函数,这是可能的吗?
我尝试重载赋值操作,因此,如果赋值不是预期值,赋值操作符函数应该将其包装在预期函数中并返回它。
#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 functionn";
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 functionn";
f = [func = std::forward<F>(func)](int x, int ) {
func(x, L"two");
};
return *this;
}
这样,您的原始main()
将编译并执行您期望的操作。
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 非常量变量只读位置的赋值
- 使用赋值运算符重载从类中返回jobject
- C++数据文件、数组和计算赋值
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 全局作用域中函数指针的赋值
- 错误:在为指针赋值时,void值没有被忽略
- 标准库类型的赋值运算符的引用限定符
- 关于 c++ 函数中指针赋值的简单问题
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 无法赋值,因为函数'operator[]'返回常量值
- 如何重载lambda赋值的operator= ?
- C++复制构造函数、赋值'operator='