Vicente J. Botet Escriba
Le 15/02/2016 07:51, Joaquin M LópezMuñoz a écrit :
Vicente J. Botet Escriba
writes: Hi Joaquin,
I have a use case where I have several keys to the same flyweight.
[...]
Let say you are writing an application that manage with some entities. You have two kind of operator that use a specific protocol and each protocol identify these entities using a key MOi. Suppose that you application use a library that has an interface that use different keys to identify these same entities, because it is using an internal protocol. You want also to have some CLI for debugging purposes that uses strings to identify these same entities.
All these keys are isomorphic so you can move from one key to the other using a specific algorithm[...]
OK, let's sketch these ideas. Let's say
key1=int
key2=char
value=std::string
and we want to minimize conversion from keyi to keyj and construction
of values, because they're all expensive operations (not in this
particular case, but you get the idea). We make the converting functions
output to the console to keep track of if/when they're called:
char key2_from_key1(int i)
{
std::cout<<"key2_from_key1\n";
return static_cast<char>(i);
}
int key1_from_key2(char c)
{
std::cout<<"key1_from_key2\n";
return static_cast<int>(c);
}
std::string value_from_key1(int i)
{
std::cout<<"value_from_key1\n";
return boost::lexical_caststd::string(i);
}
std::string value_from_key2(char c)
{
std::cout<<"value_from_key2\n";
return boost::lexical_caststd::string(c);
}
Now, we can store all of this in an internal element class like:
struct element
{
int key1;
char key2;
std::string value;
element(int i):
key1{i},
key2{key2_from_key1(i)},
value{value_from_key1(i)}
{}
element(char c):
key1{key1_from_key2(c)},
key2{c},
value{value_from_key2(c)}
{}
};
(key1,value) flyweights are easy to define:
struct element_key1
{
const int& operator()(const element& e)const{return e.key1;}
};
using key1_flyweight=flyweight