GCC shared_ptr模板错误

GCC shared_ptr Template Error

本文关键字:错误 ptr shared GCC      更新时间:2023-10-16

以下函数

#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编写函数?

只需删除那些多余的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()));
}

您过度使用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()));
}

有关进一步讨论,请参见我必须在哪里以及为什么要放置"template"answers";typename"关键字?

您不必在每次使用参数之前重写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()));
}

这是相同的问题,即类,你不写void myfunc(class MyClass &m){},而只是void myfunc(MyClass &m){}