简体   繁体   中英

C++ - (zero cost?) proxy like operator=(value) -> std::map[key]=value inside class

What is better way to create a (zero cost?) proxy like operator=(value) -> map[key]=value ?

For now I use something like that, but it's not zero cost and certainly not the best option.

And yes, target map will live guaranteed all the time that proxy lives.

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;

Thanks.

My understanding of the non-zero-cost you mention is that your proxy<1> stores a reference to the map, and therefore forces the creation of redundant storage which the compiler cannot optimise away.

I think the solution for you is to take a reference to the map at the point of use, so the compiler can use 'as if' optimisations to remove it.

For example:

#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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM