Je tente d'écrire un répartiteur dynamique pour une fonction qui est modélisée sur des valeurs entières (pas sur des types). Bien que je puisse écrire un générateur de code ou utiliser une grosse chaîne de macro pour créer la source du répartiteur, il semble qu'une solution basée sur un modèle serait plus élégante.spécialisation de modèle partiel pour l'envoi dynamique
J'ai démonté mon répartiteur à une forme simple (qui ne fait pas réellement de dispatching):
// works fine with full template specialization
template <int N>
struct TestDispatcher1D {
int f(int n) {
if (n == N) return n; // replace me with actual dispatch
TestDispatcher1D<N-1> t;
return t.f(n);
}
};
template<>
struct TestDispatcher1D<-1> {
int f(int n) { return -1; }
};
// partial template specialization is problematic
template <int M, int N>
struct TestDispatcher2D {
int f(int m, int n);
};
template<int M>
struct TestDispatcher2D<M,-1> {
int f(int m, int n) { return -1; }
};
template<int N>
struct TestDispatcher2D<-1,N> {
int f(int m, int n) { return -1; }
};
template<>
struct TestDispatcher2D<-1,-1> {
int f(int m, int n) { return -1; }
};
template <int M, int N>
int TestDispatcher2D<M,N>::f(int m, int n) {
if ((n == N) && (m == M)) return n + m; // replace me with actual dispatch
if (m < M) {
if (n < N) {
TestDispatcher2D<M-1,N-1> t;
return t(m,n);
} else {
TestDispatcher2D<M-1,N> t;
return t(m,n);
}
} else {
TestDispatcher2D<M,N-1> t;
return t(m,n);
}
}
// test code
void testIt() {
{
TestDispatcher1D<16> t;
t.f(16);
}
{
TestDispatcher1D<16>t;
t.f(0);
}
{
TestDispatcher2D<16,16>t;
t.f(8,8);
}
}
Lors de la compilation sur ce gcc 4.1.1, je reçois les erreurs suivantes:
t.cpp: In member function 'int TestDispatcher2D::f(int, int) [with int M = 16, int N = 16]': t.cpp:63: instantiated from here t.cpp:40: error: no match for call to '(TestDispatcher2D) (int&, int&)' t.cpp:63: instantiated from here t.cpp:43: error: no match for call to '(TestDispatcher2D) (int&, int&)' t.cpp:63: instantiated from here t.cpp:47: error: no match for call to '(TestDispatcher2D) (int&, int&)'
Apparemment, lorsque j'essaie de créer les objets récursifs, le compilateur ne traite pas cela comme une requête pour instancier un nouveau modèle.
Des suggestions?
Vous pouvez également écrire TestDispatcher2D <...>() .f (mn, n) –
C'est tout. Merci. J'essayais d'utiliser des trucs d'opérateur() plus tôt et j'ai raté cette correction. –
Vous pouvez même rendre f statique, vous n'avez donc pas besoin de construire un objet temporaire du tout. – sth