2013-03-26 132 views
2

以下功能GCC shared_ptr的模板錯誤

#include <memory> 

template<typename T> 
std::shared_ptr<typename T> Tail(const std::shared_ptr<typename T>& cont, size_t n) 
{ 
    const auto size(std::min<size_t>(n, cont->size())); 
    return std::shared_ptr<typename T>(new T(cont->end() - size, cont->end())); 
} 

上產生GCC 4.7.2以下錯誤。

g++ test.cpp -std=c++0x 
test.cpp:4:27: error: template argument 1 is invalid 
test.cpp:4:66: error: template argument 1 is invalid 
test.cpp: In function ‘int Tail(const int&, size_t)’: 
test.cpp:6:42: error: base operand of ‘->’ is not a pointer 
test.cpp:7:35: error: template argument 1 is invalid 
test.cpp:7:47: error: base operand of ‘->’ is not a pointer 
test.cpp:7:67: error: base operand of ‘->’ is not a pointer 

我知道cont並不看起來像一個指針,但是這對VS2012編譯很好。 如何爲gcc編寫函數?

回答

3

只是刪除這些額外的typename小號

template<typename T> 
std::shared_ptr<T> Tail(const std::shared_ptr< T>& cont, size_t n) 
{ 
    const auto size(std::min<size_t>(n, cont->size())); 
    return std::shared_ptr< T>(new T(cont->end() - size, cont->end())); 
} 
+0

感謝您的答案,爲什麼是th在? – Craig 2013-03-26 07:32:19

+0

只需你不需要它們 – deepmax 2013-03-26 07:33:04

2

你過度使用typename關鍵字。該代碼應如下所示:

template<typename T> 
std::shared_ptr<T> Tail(const std::shared_ptr<T>& cont, size_t n) 
{ 
    const auto size(std::min<size_t>(n, cont->size())); 
    return std::shared_ptr<T>(new T(cont->end() - size, cont->end())); 
} 

如需進一步討論,請參見Where and why do I have to put the "template" and "typename" keywords?

0

你不必每次使用的參數之前重寫typename,所以請將其更改爲:

template<typename T> 
std::shared_ptr<typename T> Tail(const std::shared_ptr<T>& cont, size_t n) 
{ 
    const auto size(std::min<size_t>(n, cont->size())); 
    return std::shared_ptr<typename T>(new T(cont->end() - size, cont->end())); 
} 

這是與ie類相同的問題,你不寫void myfunc(class MyClass &m){},但只是void myfunc(MyClass &m){}