简体   繁体   English

C++ 结构模板变量快捷方式定义不起作用

[英]C++ struct template variable shortcut definition does not work

template <class T>
Struct st
{
   ... 
} a<T>;

Doesnt work althogh non template shortcut works how ia tge right way to do the template shorycut?虽然非模板快捷方式不起作用,但如何使用正确的方法来执行模板快捷方式?

The C++ grammar generally lets you do type name; C++ 语法通常让你做type name; to declare a variable, where type is a type and name is a name.声明一个变量,其中type是类型, name是名称。 The syntax struct foo { } is considered a type by the grammar, which makes struct foo { } bar;语法struct foo { }被语法认为是一种类型,这使得struct foo { } bar; legal (declare a type named foo and a variable of type foo with the name bar ).合法的(声明一个名为foo的类型和一个名为barfoo类型的变量)。

However, in your example, st is not actually a type but rather a type template.但是,在您的示例中, st实际上不是类型,而是类型模板。

Type templates aren't types in their own right;类型模板本身并不是类型; they're "recipes" for the compiler to automatically create types on demand.它们是编译器根据需要自动创建类型的“配方”。 st<int> is a type, but st by itself isn't. st<int>是一种类型,但st本身不是。

Because of this, the shortcut is not grammatically correct, and is nonsensical when you think about it.因此,该快捷方式在语法上是不正确的,并且在您考虑时是荒谬的。 You can't declare a variable of something that isn't a type.您不能声明不是类型的变量。 The workaround would be to simply not use the shortcut and declare a variable separately.解决方法是简单地不使用快捷方式并单独声明一个变量。

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

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