【问题标题】:typedef for template inside template [duplicate]模板内模板的typedef [重复]
【发布时间】:2012-09-06 14:35:19
【问题描述】:

可能重复:
Where and why do I have to put the “template” and “typename” keywords?

我有一个类,它在创建对象并将所需的类作为模板参数传递时创建一个智能指针。我有另一个类需要在另一个类中使用该智能指针。

#include <iostream>
using namespace std;

//智能指针类

template<typename T>
class IntrusivePtr
{
public:
    IntrusivePtr()
    {
        cout << "IntrusivePtr()";
    }
};

//我需要一个智能指针的类,它也是模板

template<typename T>
class A
{
public:
    A()
    {
        cout << "A()";
    }
    typedef IntrusivePtr< A<T> > my_ptr;
};

//使用智能指针的类。

template<typename T>
class B
{
public:
    B()
    {
        cout << "B()";
    }

    typedef A<T>::my_ptr x;
};



int main()
{
    B<int> ob;

    return 0;
}

这可以用c++实现吗? 我知道新的 C++11 支持 typedefs 这样的事情,但我使用的是旧标准:( 编译这个我遇到了一些糟糕的错误:

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop__-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: 错误:C2146:语法错误:缺少“;”在标识符“x”之前

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop__-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: 错误:C2146:语法错误:缺少“;”在标识符“x”之前

C:\Users\jacob\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop__-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: 错误:C4430:缺少类型说明符 - 假定为 int。注意:C++ 没有 支持默认整数

编辑: 抱歉,我更改了一些内容和错误代码。这就是我想要的样子。对不起

【问题讨论】:

    标签: c++ class templates typedef smart-pointers


    【解决方案1】:
    template<typename T>
    class B
    {
    public:
        B()
        {
            cout << "B()";
        }
    
        typedef typename A< B >::my_ptr x;
    };
    

    您应该使用typename,因为my_prtdependent name

    【讨论】:

    • 要了解有关依赖名称的更多信息,请查看此excelent SO answer! :) 对我来说非常有用。
    • @PaperBirdMaster 谢谢。值得一读
    【解决方案2】:

    您的问题是A&lt;B&gt;::my_ptr 是一个依赖名称(它取决于B&lt;T&gt;,因此取决于模板参数T)。由于这个原因,编译器在解析模板时不知道它应该是类型还是变量。在这种情况下,它假定 my_ptr 不是一个类型,除非你明确地告诉它。因此你需要添加typename,就像编译器告诉你的那样:

    typedef typename A< B >::my_ptr x;
    

    更完整的解释look at this answer to a similar question

    【讨论】:

    • 感谢您的回复和链接。我现在开始阅读!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2016-01-07
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多