2009-02-18 68 views
2

我正在嘗試爲模板化爲整數值(不是類型)的函數編寫動態分派器。雖然我可以編寫代碼生成器或使用大型宏鏈來創建調度程序源,但似乎模板化解決方案會更加優雅。動態分派的部分模板專業化

我我的調度員剝離下來,以一個簡單的形式(這實際上並沒有做任何分派):

// 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: 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&)' 

很顯然,當我嘗試創建遞歸對象時,編譯器不會將其視爲實例化新模板的請求。

有什麼建議嗎?

回答

1

你根本就沒有叫你的遞歸調用的f()功能,你想「調用對象」:

你寫:

TestDispatcher2D<...> t; 
return t(m,n); 

但是你想:

TestDispatcher2D<...> t; 
return t.f(m,n); 
+0

您也可以編寫TestDispatcher2D <...>().f(mn,n) – 2009-02-18 16:16:53