GCC shared_ptr模板错误

时间:2013-03-26 07:28:14

标签: c++ templates g++ 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 个答案:

答案 0 :(得分: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()));
}

答案 1 :(得分: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?

答案 2 :(得分: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()));
}

这与课程相同,您不会写void myfunc(class MyClass &m){}而只是void myfunc(MyClass &m){}

相关问题