2010-09-30 51 views
2

我需要反覆撥打電話與代碼中的其他地方定義不同類別的模板功能,像這樣:如何創建一個數組來保存C++類(沒有實例)被反覆使用的模板函數

MyTemplateFunction<ClassOne>(&AnotherTemplateFunction<ClassOne>); 
MyTemplateFunction<ClassTwo>(&AnotherTemplateFunction<ClassTwo>); 
MyTemplateFunction<ClassThree>(&AnotherTemplateFunction<ClassThree>); 
MyTemplateFunction<ClassFour>(&AnotherTemplateFunction<ClassFour>); 

有沒有辦法爲類ClassOne,ClassTwo等創建專業化數組,因此我可以簡單地迭代數組以獲得更好的可維護性。

編輯: 我特別使用Boost.Python中的register_exception_translator函數。所以我沒有真正的選擇。它的第三方功能,我必須爲我所有的課程打電話,在我的項目中,這些課程數量超過50人。重複這樣的調用在添加或修改類時是一種混亂的體驗。

+0

爲什麼你需要做的是什麼?您可能正在尋找模式工廠:http://en.wikipedia.org/wiki/Factory_method_pattern – 2010-09-30 13:34:17

+0

@LoïcFévrier:我添加了我的理由。它的第三方功能。 – sarshad 2010-10-02 19:35:59

回答

3

像這樣的東西應該足夠

template<typename I, typename N> struct cons { }; 
struct nil { }; 

template<typename T, typename U> 
void call(cons<T, U>) { 
    MyTemplateFunction<T>(&AnotherTemplateFunction<T>); 
    call(U()); 
} 

void call(nil) { } 

typedef cons<ClassA, cons<ClassB, cons<ClassC, nil> > > conses; 
int main() { 
    call(conses()); 
} 
+0

+1:對於特定應用,手動工作通常比MPL更容易。 – Potatoswatter 2010-10-02 19:33:42

+0

這是一個很好的解決方案,沒有任何額外的依賴。我學到了一些新的東西。謝謝。 – sarshad 2010-10-04 14:04:47

4

你應該看看Boost.MPL,特別是sequences

+0

+1在我看來,如果使用Boost.MPL來解決不僅僅是一個簡單的重構問題,這是一個很好的選擇。對於我的情況,我不想爲一個非常小的問題添加另一個依賴項。 – sarshad 2010-10-04 13:52:16

相關問題