2013-11-20 77 views
0

我有三類:實例化模板類與模板參數

//Template class for function 1 
template<class P> class wrap4{ 
    P p; 

public: 
    wrap4(P&& p1) : p(std::forward<P>(p1)) {} 

    double f(double x){ 
     return p.FN(x); 
    } 

}; 

//Simple concrete parameter 
struct Parameter{ 
    double FN(double x){ 
     return x; 
    } 

}; 

//Method used in the program 
template<class Function> class B { 
    Function F; 
public: 
    B(Function && f) : F(std::forward<Function>(f)) {} 
    double use(double x){ 
     return F.f(x); 
    } 
}; 

template<class Function> B<Function> make_B(Function && F){ return B<Function>{std::forward<Function>(F)}; } 
template<class P> B<P> make_wrap4(P && F){ return B<P>{std::forward<P>(F)}; } 

基本上,我想插wrap4B,但這樣做,我有Parameter來實例化。我已經試過如下:

auto A = make_B(make_wrap4{Parameter p}); 

但這不起作用,我得到的編譯器錯誤

error: conversion from 'B<B<Parameter> >' to non-scalar type 'B<wrap4<Parameter> >' requested 

當然,這是一個愚蠢的例子,因爲我知道我可以只實現BParameter,但當然我試圖做一些更復雜的事情,從長遠來看,我真的需要一個B來接受一個不承認默認構造函數作爲參數的模板類。

我需要在這裏實現模板模板參數嗎?

回答

1

你有,你應該能夠從錯誤信息現貨副本&粘貼錯誤:

template<class P> B<P> make_wrap4(P && F){ return B<P>{std::forward<P>(F)}; } 

應該

template<class P> wrap4<P> make_wrap4(P && F){ return wrap4<P>{std::forward<P>(F)}; } 
//    ^^ here        ^^ and here 

,然後你應該叫make_wrap4像一個功能,即不與一個初始化列表。


一個小旁註:你沒有三個班,你有一個類和兩個類模板。它也不是模板類,因爲註釋狀態爲wrap4

  • wrap4類模板
  • wrap4<int>wrap4<Parameter>,你通過實例化類模板得到的。有些人會稱模板類別爲
+0

謝謝!這是一個相當遲鈍的錯誤:D另外,謝謝你的筆記。 – Plamen

+1

是的,很抱歉被挑剔,但有時候這樣的事情會使理解和不理解問題之間的區別,特別是在SO上) –

+0

你是絕對正確的。當我說謝謝時,我很誠實!我對模板非常陌生 - 我認爲這很出色 - 我仍然有許多細微差別。 – Plamen