2014-12-05 72 views
0

我想我的模板化派生類der從foo繼承。 這只是一個測試代碼,我想看看我是否在這裏採取了正確的方法 der類本身是模板化的,我想要做的是在初始化列表der類中傳遞其基類foo的模板類型。我使用下面的代碼從另一個模板化結構繼承的模板化結構

template<typename t , typename u> 
struct foo 
{ 
    void foo_method(t inp , u out) 
    { 
     std::cout << inp + out << "\n"; 
    } 
}; 


template <typename m> 
struct der : public foo<t,u> //Error t was not declared in the correct scope 
{ 
    der():foo<t,u>(int,int)//I want to specify the types for the base class in initialization list 
    { 

    } 
}; 


int main() 
{ 
    der<std::string> d; 

} 

現在,當我嘗試運行上面的代碼,我得到

Error t was not declared in the correct scope 

上,我怎麼能解決這個問題有什麼建議?

+0

轉載,編譯器應該如何知道什麼是'富<>'要從如果你不提供模板參數繼承? – 0x499602D2 2014-12-05 05:03:22

+0

你的問題沒有多大意義。 'foo'沒有兩個參數的構造函數,所以你想傳遞給它的是什麼? 「t」和「u」應該是什麼? – Praetorian 2014-12-05 05:09:17

回答

3

我認爲這是你在找什麼:

template <typename m> 
struct der : public foo<int,int> 
{ 
    der():foo<int,int>() 
    { 

    } 
}; 
+0

當然,編譯器生成的版本已經調用了基類default-ctor。 – 0x499602D2 2014-12-05 05:04:51

+0

然後我們不需要foo ()。我想知道是否可以在初始化列表中指定它們。我對此很好奇 – MistyD 2014-12-05 05:06:19

+0

@MistyD:如果你的意思是*只*在那裏指定他們,那麼不,但我不太清楚你真的想要完成什麼。 – 2014-12-05 05:07:35

1

這是不是你想要做什麼?我無法確切地告訴你在你的問題中要求什麼。

http://ideone.com/dBCkQb

#include <iostream> 

using namespace std; 

template<typename t, typename u> 
struct foo{ 
    foo(t a, u b) : x(a),y(b) 
    { 

    } 
    t x; 
    u y; 
}; 

template <typename m, typename t, typename u> 
struct der : public foo<t,u>{ 
    der(m a, t b, u c) :foo<t,u>(b,c), z(a) 
    { 

    } 
    m z; 
}; 


int main() { 
    der<int,double,float> myder(1,1.03,2.05); 
    cout << myder.x << endl << myder.y << endl << myder.z << endl; 
    return 0; 
}