2010-10-31 170 views
1

在代碼:如何將參數傳遞給策略的構造函數?

template<class T> 
struct FactorPolicy 
{ 
    T factor_; 
    FactorPolicy(T value):factor_(value) 
    { 
    } 
}; 

template<class T, template<class> class Policy = FactorPolicy> 
struct Map 
{ 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
     Map<int,FactorPolicy> m;//in here I would like to pass a double value to a 
//FactorPolicy but I do not know how. 
     return 0; 
    } 

編輯 [馬克H]

template<class T, template<class> class Policy = FactorPolicy> 
struct Map : Policy<double> 
{ 
    Map(double value):Policy<double>(value) 
    { 
    } 
}; 
+0

爲什麼你想要它? – 2010-10-31 19:56:20

+0

@Alexey如果你看看FactorPolicy的ctor,有一個arg被傳遞,我希望能夠在聲明變量Map時傳遞這個值。像這樣:Map 2010-10-31 20:02:12

回答

0

一種方式是提供採取模板ARG與策略中使用成員函數模板。例如:

template<class T, template<class> class Policy = FactorPolicy> 
struct Map 
{ 
    template <typename V> 
    void foo(const Policy<V> &p) 
    { 
    } 
}; 

然後,在主:

Map<int,FactorPolicy> m; 

m.foo(FactorPolicy<double>(5.0)); 

另一種可能性是將其指定爲地圖模板實例的一部分,通過加入第三模板ARG到地圖:

template<class T, template<class> class Policy = FactorPolicy, 
     class V = double> 
struct Map 
{ 
    void foo(const V &value) 
    { 
    Policy<V> policy(value); 
    } 
}; 

Then:

Map<int,FactorPolicy,double> m; 

m.foo(5.0); 
+0

@Michael no我沒有,它是一個模板模板類 – 2010-10-31 19:51:57

+0

好吧,我爲你指定的_tmain函數工作了嗎?因爲底線是你無法定義一個變量而不指定所有的(實際)模板參數。 – 2010-10-31 19:52:49

+0

@Michael你的更新,我不是100%肯定,但如果我宣佈模板模板,我不必提供模板decl參數。但正如我所說,我不是百分之百確定。 – 2010-10-31 19:54:17

0

如果您要傳遞double,則需要在Map內部FactorPolicy的類型參數爲double,除非您使FactorPolicy構造函數接受double。我不認爲這是你想要的。你必須通知Map策略需要一個double,所以首先添加該類型的參數。其次,我認爲你需要從Map構造函數轉發實際的double值。

template<class T, typename U, template<class> class Policy = FactorPolicy > 
struct Map { 
    Map(U val) { 
     policy_ = new Policy<U>(val); 
    } 

    Policy<U>* policy_; 
}; 

int main() 
{ 
    Map<int, double, FactorPolicy> m(5.63); 
    return 0; 
} 
+0

@Mark如果我想將因子值傳遞給ctor,我會做得更簡單 - 您不必指定U型。 – 2010-10-31 20:44:15

+0

對於你所聲稱的,你需要將它定義爲'template >'。否則Map如何知道FactorPolicy需要雙重?它不能簡單地從參數的類型中推斷出來,你必須在某個地方明確地說明類型。 – 2010-10-31 20:48:49

+0

@Mark給我秒 – 2010-10-31 20:52:06

相關問題