【问题标题】:Is this name lookup in dependent base class with VC++ 2010 non-standard?这个名称在 VC++ 2010 非标准的依赖基类中查找吗?
【发布时间】:2012-06-16 13:53:01
【问题描述】:

以下代码无法在 Ideone 或 Codepad 上编译,产生如下错误:

'X' 未在此范围内声明

但在 VC++ 2010 上可以:

    #include <iostream>
    #include <typeinfo>

    template<typename T>
    struct Base
    {
            typedef T X;
    };

    template<typename T>
    struct Derived
    :
            Base<T>
    {
            static void print()
            {
                    std::cout << typeid(X).name() << "\n";
            }
     };

    int main()
    {
            Derived<int>::print();
            Derived<char>::print();
            Derived<float>::print();
            return 0;
    }

在哪里打印intcharfloat。我应该将代码更改为:

    template<typename T>
    struct Derived
    {
            typedef Base<T> B;
            static void print()
            {
                    std::cout << typeid(typename B::X).name() << "\n";
            }
     };

为了符合标准?

【问题讨论】:

  • 你的意思是在第二个例子中放弃继承吗?
  • @juanchopanza 是的,我的意思是放弃它,因为该示例来自一个真实项目,其中Base 依赖于更多模板参数,因此内部typedef 使代码更多一点可读。可读性实际上是我在 MSVC++ 中尝试继承但在 g++ 上失败的原因。
  • this question的答案相同。

标签: c++ templates base-class class-members name-lookup


【解决方案1】:

如果你的意思是这样的(注意你在你的例子中已经放弃了继承):

template<typename T>
struct Derived : Base<T>  {
  static void print() {
    std::cout << typeid(typename Base<T>::X).name() << "\n"; 
  }
};

那么是的,这是符合标准的代码。但请注意,typeid(some type).name() 的结果取决于实现。在 GCC 上,您的 main 生成 icf

【讨论】:

    【解决方案2】:

    $ g++ -Wall test.cpp
    test.cpp:在静态成员函数'static void Derived::print()'中:
    test.cpp:15:37: 错误:'X' 未在此范围内声明

    $ g++ --version
    g++ (SUSE Linux) 4.6.2

    【讨论】:

    • 您能否提供一些上下文来说明这意味着什么,以及它与问题的关系?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2021-12-09
    相关资源
    最近更新 更多