C++ 在‘之前应为主表达式;结构&x2019;

C++ 在‘之前应为主表达式;结构&x2019;,c++,struct,C++,Struct,GCC 8.3.0和clang 9.0.1都未能编译以下简短示例代码: #include <cstdlib> template <typename T> struct mystruct { T data; }; int main (const int argc, const char * const * const argv) { int ret = EXIT_SUCCESS; auto elem1 = struct mystruct<bool&g

GCC 8.3.0和clang 9.0.1都未能编译以下简短示例代码:

#include <cstdlib>

template <typename T>
struct mystruct {
  T data;
};

int main (const int argc, const char * const * const argv) {
  int ret = EXIT_SUCCESS;

  auto elem1 = struct mystruct<bool> { }; // Doesn't compile.
  auto elem2 = mystruct<bool> { }; // Does compile.

  return (ret);
}
#包括
模板
结构mystruct{
T数据;
};
int main(常量int argc,常量char*const*const argv){
int ret=退出成功;
auto elem1=struct mystruct{};//未编译。
auto elem2=mystruct{};//编译。
返回(ret);
}
出现的错误消息:

teststruct.cpp:在函数“int main(int,const char*const*)”中:
teststruct.cpp:11:16:错误:应在“struct”之前使用主表达式
auto elem1=struct mystruct{};//不编译。
^~~~~~
teststruct.cpp:11:16:错误:应为表达式
auto elem1=struct mystruct{};//不编译。
^
我不明白为什么第一个表达式似乎是某种非法语法

<> P>>我认为,结构> /COD>关键字在C++ +<强>中基本上可以省略,除非< /强>存在歧义。这往往会发生(例如,对于
[struct]stat
,它可以是一个结构,也可以是一个函数),因此
struct
关键字可以而且应该用于消除这种情况下的歧义

然而,在我的例子中,使用
struct
关键字是完全有害的,我从来没有想到过这一点


由于两个不同的编译器以完全相同的方式拒绝代码,我最好的猜测是我缺少了一些信息,而不是一个bug。

类型(…)
这样的
语法需要一个单一的、非精心设计的类型说明符。这可能相当复杂:

auto x=typename A::template B<int>();  // OK
当然,可以通过
decltype
或引入typedef名称来处理此类情况:


只是一个猜测,但我相信您只是在调用mystruct的构造函数,所以将struct关键字放在那里对编译器没有意义。我在这段代码中得到了相同的错误:struct test{int data;}int main(){auto temp=struct test;}您可以添加括号作为
auto elem1=(struct mystruct){。是的,但不是。我正在创建一个类型为
[struct]mystruct
的新对象,该对象初始化为初始值设定项列表中提供的值(该值恰好为空,因此初始化为零),然后复制到原始变量。当然,副本是多余的,但这不是重点。但是,到目前为止,您的观点很感兴趣,编译器可能不会将
struct mystruct
视为一个类型,而将其视为其他类型,这可以通过在parens中包装该类型来解决。还是。。。这听起来很奇怪。这对于创建任何多单词类型的临时文件都是一样的@宋元耀:这是一个复合文字,它不是C++(但经常支持C99兼容性)。在Type的简单模板ID中定义的模板名称应该是一个标识符。@ YA99:听起来不错,但是我不确定你想从中得出什么结论。只要把链接粘贴到doc。代码>:)
// All bad:
auto a=int*{};
auto b=const int();
auto c=struct X{};  // a class definition?
auto d=struct Y {}();  // still not allowed
auto e=signed char();

auto f=signed();  // OK, means int
void f(void());
void f(int*);
struct x {};
void g(x);
void g(unsigned long);
void h() {
  // Ambiguous:
  // f(nullptr);
  // Illustrative of the parsing difficulty:
  // f(void(*)()());
  f(decltype(&h)());
  int x;  // oh noes
  using y=struct x;
  g(y());
  g(decltype(1ul)());  // same as g(0);
}