Hallo zusammen,
Ich habe eine Datenstruktur die sich am besten durch einen Tupel darstellen lässt. Außerdem verwende ich an einigen Stellen etwas Metaprogrammierung, darum habe ich mich entschlossen, das Ganze gleich mit boost::fusion umzusetzen. Nun brauche ich an einigen Stellen im Programm die Funktionalität, dass ich alle Elemente einer Tupelinstanz mit allen Elementen einer anderen Instanz 'verwurschteln' muss.
Ich habe mir dazu folgendes einfallen lassen:
#include <boost/fusion/include/container.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include<iostream>
namespace fusion = boost::fusion;
typedef fusion::vector<double,int> mylist;
template<typename T1, typename T2> void foo(T1 & x1, T2 & x2);
template<> void foo<int,int>(int &x1, int &x2){
std::cout<<"int "<<x1<<" trifft int "<<x2<<std::endl;
}
template<> void foo<int,double>(int &x1, double &x2){
std::cout<<"int "<<x1<<" trifft double "<<x2<<std::endl;
}
template<> void foo<double,int>(double &x1, int &x2){
std::cout<<"double "<<x1<<" trifft int "<<x2<<std::endl;
}
template<> void foo<double,double>(double &x1, double &x2){
std::cout<<"double "<<x1<<" trifft double "<<x2<<std::endl;
}
template<typename T1> struct inner_loop{
inner_loop(T1 &xx):x1(xx){}
template<typename T2> void operator()(T2 & x2)const{
foo<T1,T2>(x1,x2);
}
private:
T1 &x1;
};
template<typename T2> struct double_loop{
double_loop(T2 &TT):T(TT){}
template<typename T1> void operator()(T1 & x)const{
for_each(T,inner_loop<T1>(x));
}
private:
T2 &T;
};
int main(){
mylist liste(1.1,2);
mylist liste2(2.2,1);
for_each(liste, double_loop<mylist>(liste2));
}
Dies gibt wie gewollt aus:
double 1.1 trifft double 2.2
double 1.1 trifft int 1
int 2 trifft double 2.2
int 2 trifft int 1
Doch wie man wahrscheinlich leicht sieht, mangelt es mir doch klar an Erfahrung in Metaprogrammierung und ich wollte wissen, ob es da elegantere Lösungsmöglichkeiten für mein Problem gibt oder was man an meiner Variante verbessern kann.
Eine Sache die mich an meiner Lösung ziemlich stört: Ich musste die Funktion foo() fest in inner_loop() einbauen. Brauche ich die Funktionalität an anderer Stelle wieder, so muss ich ein neues Schleifenkonstrukt bauen. Kann ich foo() irgendwie als Funktor an double_loop() weitergeben? Ich wüsste jetzt nicht wie, weil ich beim Aufruf von double_loop() ja noch nicht weiß, was am Ende die Templateparameter von foo() sind