2013-02-22 110 views
1

我有一個類,它具有公共模板方法。 這個類有2個行爲策略,我想通過類模板傳遞。模板類在C++中的模板方法的使用

template<class Strategy> 
class SomeClass { 
public: 
    template<class B> 
    void ProcessType(){} 
}; 

// And do something like this: 
SomeClass<Strategy1> sc(); 
sc.ProcessType<SomeClassType>(); 
sc.ProcessType<SomeClassType2>(); 

SomeClass<Strategy2> sc2(); 
sc2.ProcessType<SomeClassType>(); 
sc2.ProcessType<SomeClassType2>(); 

但是這段代碼不能編譯。我需要像這樣保持用法(僅通過策略操作)。

回答

4

這就是問題所在:

SomeClass<Strategy1> sc(); 

這是一個叫做sc函數,它沒有參數,並返回一個SomeClass<Strategy1>的聲明。這通常被稱爲令人煩惱的解析(但不是most vexing parse)。你想要的是:

SomeClass<Strategy1> sc; 
+0

謝謝,它編譯。但不是建立。我嘗試在.cpp文件中實現此方法,併爲此方法提供鏈接錯誤(未解析的外部...)。 – deeptowncitizen 2013-02-22 11:07:18

+0

我這麼做:http://stackoverflow.com/questions/886206/out-of-declaration-template-definitions-for-template-method-in-template-class – deeptowncitizen 2013-02-22 11:08:03

+0

@deeptowncitizen類模板的成員函數必須在頭文件中定義。編譯器需要能夠看到所有翻譯單元中的定義。 – 2013-02-22 11:55:45