shared_ptr of a template class using gcc 4.6

shared_ptr of a template class using gcc 4.6

本文关键字:using gcc class template ptr of shared      更新时间:2023-10-16

试图在c++11 中实现以下功能

template< class A >
    class B{
         std::shared_ptr< A > a_shared_ptr;
    };
B< int > b;

有可能吗?

正在获取以下错误

..//src/threading/note.h:26:错误:ISO C++禁止声明没有类型的"shared_ptr"../../src/threading/note.h:26:错误:"::"的使用无效../../src/threading/note.h:26:错误:应为";"在'<'之前令牌

是的,这是可能的

由于std::shared_ptr是C++11的一个新特性,您必须在编译器上启用对C++11的支持。在GCC下,选项为:-std=c++0x-std=gnu++0x

如果我不启用这些功能,我会得到与您完全相同的错误。

另一点是:不要忘记包括std::shared_ptr:的标题

#include <memory>

只需包含std::shared_ptr的头,它就可以很好地编译:

#include <memory>
template< class A >
class B{
    std::shared_ptr< A > a_shared_ptr;
};
int main()
{
    B< int > b;
    return 0;
}