I have the following class Sample. Say, I wanna perform some heavy computation using member variable var
and cache the result in case I will do the same computation again. I also guarantee that non-cached variable var
be const, and if not, I wanna get an error at the compilation time. So, what I want to do is to const-nize heavy_compuation
in a way that mutation of only cache
is accepted. Is there any way to do this kind of thing?
#include<iostream>
#include<map>
class Sample
{
public:
Sample(int var_) : var(var_){}
std::map<int, int> cache;
int var;
int heavy_computation(int x)
{
std::map<int, int>::iterator iter = cache.find(x);
if(iter == cache.end()){ // cache doesn't exist
int y = var + x;
cache[x] =y;
return var;
}
std::cout << "cached one" << std::endl;
return iter->second;
}
};
int main(){
Sample s(0);
s.heavy_computation(1);
s.heavy_computation(1);
}