(型ではなく) 整数値でテンプレート化された関数の動的ディスパッチャを作成しようとしています。コード ジェネレーターを作成するか、大きなマクロ チェーンを使用してディスパッチャー ソースを作成することもできますが、テンプレート化されたソリューションの方が洗練されているようです。
ディスパッチャを単純なフォームに落とし込みました (これは実際にはディスパッチを行いません):
// 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);
}
}
これを gcc 4.1.1 でコンパイルすると、次のエラーが発生します。
t.cpp: メンバー関数 'int TestDispatcher2D::f(int, int) [with int M = 16, int N = 16]': t.cpp:63: ここからインスタンス化 t.cpp:40: エラー: '(TestDispatcher2D) (int&, int&)' の呼び出しに一致しません t.cpp:63: ここからインスタンス化 t.cpp:43: エラー: '(TestDispatcher2D) (int&, int&)' の呼び出しに一致しません t.cpp:63: ここからインスタンス化 t.cpp:47: エラー: '(TestDispatcher2D) (int&, int&)' の呼び出しに一致しません
どうやら、再帰オブジェクトを作成しようとすると、コンパイラはこれを新しいテンプレートをインスタンス化する要求として処理していません。
助言がありますか?