什么是创建(零成本?)代理的更好方法,例如 operator=(value)
-> map[key]=value
?
目前我使用类似的东西,但它不是零成本,当然也不是最好的选择。
是的,目标 map 将保证在代理存在的所有时间都存在。
template <int key>
class proxy {
public:
std::map<int,int> & proxy_m;
proxy(std::map<int,int> & m) : proxy_m(m) {}
void operator=(int value) {
proxy_m[key] = value;
}
};
class A {
public:
std::map<int,int> m;
proxy<1> proxy_one {m};
};
...
A a;
a.proxy_one = 1; // a.m[1] = 1;
谢谢。
最佳答案
我对你提到的非零成本的理解是你的代理<1>存储了对 map 的引用,因此强制创建编译器无法优化的冗余存储。
我认为您的解决方案是在使用时引用 map ,这样编译器就可以使用“好像”优化来删除它。
例如:
#include <map>
#include <utility>
template <int key>
class proxy {
public:
std::map<int,int> & proxy_m;
proxy(std::map<int,int> & m) : proxy_m(m) {}
void operator=(int value) {
proxy_m[key] = value;
}
};
template<int N>
using key = std::integral_constant<int, N>;
class A {
public:
std::map<int,int> m;
template<int N>
auto get_proxy(key<N>) {
return proxy<1>(m);
}
};
int main()
{
A a;
// in reality no proxy<> will be created and no reference taken
// provided you enable optimisations.
a.get_proxy(key<1>()) = 1;
}
关于C++ -(零成本?)类似 operator=(value) 的代理 -> std::map[key]=value inside class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501273/