简体   繁体   English

C ++类相关的typedef在类外部声明

[英]c++ class dependant typedef declared outside class

I have two classes, which I shall call classA and classB. 我有两个类,分别称为classA和classB。

In classA I have some types defined, such as T5. 在classA中,我定义了一些类型,例如T5。
In classB I use such types defined in classA. 在classB中,我使用classA中定义的此类类型。

In order to avoid writing 为了避免写作

typename classA<T1,T2>::T5

throughout my code, I want to create a class indipendent type, which I would be able to call directly by simply its name - templatedClassA in the example. 在我的整个代码中,我想创建一个类独立类型,在示例中,我可以直接通过其名称-templatedClassA直接调用它。 The template paremeters would still be parametric, and I would define them in future projects using classA and classB. 模板参数仍然是参数化的,我将在以后的项目中使用classA和classB对其进行定义。

#include <cstdlib>
#include <iostream>

using namespace std;

//classA
template <class T1, class T2>
class classA
{
 public:  
 typedef T1 T5;
 classA();
};

template <class T1, class T2>
classA<T1,T2>::classA(){}
//end classA

template <class T1, class T2>
typedef classA<T1,T2> templatedClassA;

template <class T1, class T2>
typedef typename classA<T1,T2>::T5 T6;






//classB
template <class T3, class T4>
class classB
{
 public:
 classB();
};

template <class T3, class T4>
classB<T3,T4>::classB(){}
//end classB



int main(int argc, char *argv[])
{

    classB<int, double> classBInstance;

    system("PAUSE");
    return EXIT_SUCCESS;
}

When compiling the above code, I get the following two errors: 编译上面的代码时,出现以下两个错误:

template declaration of `typedef class classA<T1, T2> templatedClassA'
template declaration of `typedef typename classA<T1, T2>::T5 T6'.

What am I doing wrong? 我究竟做错了什么?

Templates cannot be used in typedef declarations. 模板不能在typedef声明中使用。 You have to wrap the declaration in a class like this: 您必须将声明包装在这样的类中:

template <class T1, class T2>
class templatedClassA {
    typedef classA<T1, T2> type;
};

template <class T1, class T2>
class T6 {
   typedef typename classA<T1, T2>::T5 type;
};

In C++11 you can use the using alias as shown in the other answer. 在C ++ 11中,您可以使用using别名,如其他答案所示。

In C++11, you may do: 在C ++ 11中,您可以执行以下操作:

template <class T1, class T2>
using templatedClassA = classA<T1, T2>;

template <class T1, class T2>
using T6 = typename classA<T1, T2>::T5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM