GCC shared_ptr模板错误
GCC shared_ptr Template Error
以下函数
#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){}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- 尝试 ptr->map.clear() 时出现分段错误
- 为什么在将常量 ptr 分配给常量引用时没有收到编译错误?
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 使用std :: String ptr的错误打印std :: String
- 尝试为图像缓冲区分配内存时 ptr 值错误
- 在记录错误时取消引用 ptr 的设计是错误的
- 在将值分配给 CString 时获取<错误 Ptr> 和无效值
- BSTR bstrRtf = 0xcccccccccccccccc <调试时错误 Ptr>( = CXX0030:错误:无法计算表达式)
- 非ptr新声明符中的错误表达式
- 在另一个线程中分配唯一ptr的错误
- 此指令中的错误 C2415 "MOV Incoming_Packet_Length,DWORD PTR SS:[EBP-14]"
- C ++ STL 字符串<错误的 PTR>但有字符串值是什么意思?
- Linux中的c++运行时错误::glibc检测到free():无效的下一个大小(快速):堆栈具有void ptr元素
- 将输入字符串转换为字符* <错误 Ptr>
- char*中的C++错误PTR(无法计算表达式)
- 将字符串引用作为参数传递时Ptr错误
- 提升文件系统错误(temp_directory_path返回<错误 Ptr>)