C++使用别名访问嵌套类型(使用 vs typedef)

C++ accessing nested type using alias (using vs typedef)

本文关键字:使用 vs typedef 嵌套类型 别名 访问 C++      更新时间:2023-10-16

今天我们发现了一个令人困惑的C++11别名声明行为。下面是示例:

template<typename T>
struct Q
{
    typedef T t;
};
template<typename T>
void foo(Q<T> q)
{
    using q_t = Q<T>; 
    //typedef Q<T> q_t; // if we uncomment this and comment 'using' the example compiles
    typename q_t::t qwe; // <<<<<<<<<< Error: no type named ‘t’ in ‘using q_t = struct Q<T>’
}
int main(int argc, char *argv[])
{
    Q<int> q;
    foo(q);
    return 0;
}

ISO 14882(C++11)规定这两个声明必须具有相同的语义(第145页)。

但是,如果我们q_t声明了"using",则该示例不会使用 GCC 4.7.2(Debian Wheezy)和 GCC 4.7.3(Ubuntu 13.04)进行编译,但将"using"语句替换为"typedef"语句使其编译。

是GCC中的错误还是我们只是误解了标准?

这似乎是GCC 4.7的错误。

这是我编译代码的测试,它使用 gcc 4.8.1 工作

因此,正如规范所说:

using q_t = Q<T>;
// is equivalent to this 
typedef Q<T> q_t;
使用

--std=c++11 使用 g++ 4.8.1 为我编译得很好