I try to implement visitor pattern with templates.
My code is:
struct some_class
{
char field1;
bool field2;
some_class()
: field1('a')
, field2(0)
{
}
};
struct unnamed_lambda
{
template<typename T>
T operator()(T x) const { return x + 1; }
};
struct unnamed_lambda2
{
template<typename T>
T operator()(T x) const { return x + 2; }
};
template<class processor>
void reflect(processor & p, some_class& sc)
{
reflect(p, sc.field1, "field1");
reflect(p, sc.field2, "field2");
}
template<class t>
void reflect(unnamed_lambda & p, t& val, string str)
{
cout << val << endl;
}
void print_helper()
{
unnamed_lambda lambda = unnamed_lambda{};
some_class sc;
reflect(lambda, sc);
}
template<class t>
void reflect2(unnamed_lambda2 & p, t& val, string str)
{
cout << val + 1 << endl;
}
void print_helper2()
{
unnamed_lambda2 lambda = unnamed_lambda2{};
some_class sc;
reflect(lambda, sc);
}
int main()
{
print_helper();
print_helper2();
return 0;
}
I want to have some class that defines traversal order of its fields. In my case, it is a void reflect(processor & p, some_class& sc)
function. In addition, I want to have a set of actions on this class. In my case, It is print_helper
and print_helper2
.
In order to correlate the operation and the desired action, I create two dumb structure: unnamed_lambda
and unnamed_lambda2
. These structures do nothing. It is a workaround.
Why do this code smell so bad? There is a reason. The signature function void reflect(processor & p, some_class& sc)
is fixed.
In other words, I can do everything except change the signature of this function and its implementation. More I can not change the some_class
class.
I got confused. I'll be glad for any help on my question.
Aucun commentaire:
Enregistrer un commentaire