最近,我开始使用C++ 11,并对类关键字的特殊用法提出了一些问题。我知道它用于声明类,但是有两个实例我不明白:
Method<class T>();和
class class_name *var;为什么我们在第一个示例中按关键字类在typename之前,以及关键字在第二个示例中做什么指针?
发布于 2014-10-06 13:11:16
这被称为精化类型说明符,通常只有在类名“隐藏”或“隐藏”并且需要显式时才有必要。
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发布于 2014-10-06 13:15:06
除了其他答案之外,您还可以使用class关键字在使用点转发声明类。例如,代替:
class SomeClass;
SomeClass* p = some_function();你可以写:
class SomeClass* p = some_function();这通常与模板和标记分派一起使用,当模板实例化需要一个标记类型参数时,该参数的唯一目的是使实例化成为唯一的类型,并且标记不必是一个完整的类型。例如:
template<class Tag> struct Node { Node* next; };
struct Some : Node<class Tag1>, Node<class Tag2> {};https://stackoverflow.com/questions/26216868
复制相似问题