我最近开始使用C ++ 11,并对 class 关键字的特殊用途提出了一些问题。我知道它用于声明一个类,但有两个我看到的实例,我不明白:
Method<class T>();
和
class class_name *var;
为什么我们在第一个示例中使用关键字 class 在typename之前,并且第二个示例中的关键字是什么?
答案 0 :(得分:11)
这被称为精心设计的类型说明符,通常只有在你的班级名称是&#34;阴影&#34;或者&#34;隐藏&#34;你需要明确。
class T
{
};
// for the love of god don't do this
T T;
T T2;
如果你的编译器是智能的,它会给你这些警告:
main.cpp:15:5: error: must use 'class' tag to refer to type 'T' in this scope
T T2;
^
class
main.cpp:14:7: note: class 'T' is hidden by a non-type declaration of 'T' here
T T;
^
如果您的课程之前没有定义,它也将作为前瞻性声明。
例如:
template <typename T>
void Method()
{
using type = typename T::value_type;
}
Method<class T>(); // T is a forward declaration, but we have not defined it yet,
// error.
否则没有必要。
class T
{
public:
using value_type = int;
};
// method implementation...
Method<T>();
Method<class T>(); // class is redundant here
答案 1 :(得分:2)
除了其他答案之外,您还可以class
关键字转发在使用地点声明一个类。例如。而不是:
class SomeClass;
SomeClass* p = some_function();
你可以写:
class SomeClass* p = some_function();
这通常与模板和标签分派一起使用,当实例化模板需要标记类型参数时,其唯一目的是使实例化成为唯一类型,并且标记不必是完整类型。 E.g:
template<class Tag> struct Node { Node* next; };
struct Some : Node<class Tag1>, Node<class Tag2> {};