2017-08-15 61 views
0

我正在嘗試將模板方法添加到模板類。我提到this答案,但是語法不起作用。我添加了第二種方法,我稱之爲tester模板。這是我在模板類中聲明模板方法

template <typename t,typename u> 
struct foo { 

    void test(); 

    template<typename v> 
    void tester(v lhs); 
}; 

template<typename t,typename u> 
void foo<t,u>::test() { 
    std::cout << "Hello World" ; 
} 

template<typename t,typename u> 
template<typename v> 
void foo<t,u>::tester<v>(v lhs) { 
    std::cout << "Hello world " << lhs ; 
} 

int main() 
{ 
    foo<int,int> t; 
    t.test(); 
    t.tester<int>(12); 
} 

我得到的方法tester的錯誤,這是錯誤,我得到

main.cpp:20:31: error: non-type partial specialization 'tester<v>' is not allowed 
void foo<t,u>::tester<v>(v lhs) { 

任何建議,爲什麼我收到此錯誤,或者是我可能是做錯了?在下面的更正後的代碼

+0

如果你想專門爲測試儀''然後刪除'類型名稱v',還可以使用'int'爲'lhs'參數 – KayEss

+0

我想看看我是否可以模擬'tester'方法。如果後來我想'lhs'是'string'類型的話呢? –

+0

然後你不是想部分專門化,那麼爲什麼你有'tester '而不是'tester '? – KayEss

回答

1

評論在線:

#include <iostream> 

template <typename t,typename u> 
struct foo { 

    void test(); 

    template<typename v> 
    void tester(v lhs); 
}; 

template<typename t,typename u> 
void foo<t,u>::test() { 
    std::cout << "Hello World" ; 
} 

/* 
* change made to this template function definition 
*/ 
template<typename t,typename u> 
template<typename v> 
void foo<t,u>::tester(v lhs) { 
    std::cout << "Hello world " << lhs ; 
} 

int main() 
{ 
    foo<int,int> t; 
    t.test(); 
    t.tester<int>(12); 
}