在 G++ 4.8 中,typeof 仍然不能与 "::" 一起使用

In G++ 4.8, typeof still cannot be used with "::"

本文关键字:不能 一起 G++ typeof      更新时间:2023-10-16

以下代码不在G++4.8 下编译

#include <vector>
using namespace std;
int main() {
    vector<int> v;
    typeof(v)::iterator it;
}

如果我将typeof替换为decltype,它可以正常工作。我知道一个模板结构的变通方法

template<class T> struct Self {
    typedef T Type;
};

然后

Self<typeof(v)>::Type::Iterator it;

但仍然很烦人。

这是一个应该报告的错误吗?或者这是一个功能?

这里我只是写下n.m.的评论作为答案,并对其进行了一点扩展。

在C++11中,我们有decltype,它可以与::一起使用。考虑以下代码:

#include <vector>
using namespace std;
int main() {
    vector<int> v;
    decltype(v)::iterator it;
}

上面的代码使用g++ -std=c++11 -Wall -Wextra -pedantic typeof.cpp进行了干净的编译。

由于decltype是标准的,并且已经得到了gcc 4.3(2008年发布,6年前)的支持,因此绝对没有理由使用gcc扩展typeof。如果您使用decltype,您的代码将是标准的,因此是可移植的。