c++ - 如何理解 C++ 中的依赖名称

标签 c++

我通常在模板的上下文中遇到“依赖名称”这个术语。但是,我很少接触后者。因而自然想了解更多关于从属名称的概念。

在模板的上下文中和模板之外,您如何理解它?强烈鼓励树立榜样!

最佳答案

依赖名称的特点是对模板参数的依赖。简单的例子:

#include <vector>

void NonDependent()
{
  //You can access the member size_type directly.
  //This is precisely specified as a vector of ints.

  typedef std::vector<int> IntVector;  
  IntVector::size_type i;

  /* ... */
}

template <class T>
void Dependent()
{

  //Now the vector depends on the type T. 
  //Need to use typename to access a dependent name.

  typedef std::vector<T> SomeVector;
  typename SomeVector::size_type i;

  /* ... */
}

int main()
{
  NonDependent();
  Dependent<int>();
  return 0;
}

编辑:正如我在下面的评论中提到的,这是一个关于使用频繁出现的依赖名称的特殊情况的示例。有时,管理从属名称使用的规则并不是人们本能所期望的。

例如,如果您有一个从依赖基类派生的依赖类,但在基类的名称显然不依赖于模板的范围内,您可能会收到如下所示的编译器错误。

#include <iostream>

template <class T>
class Dependent
{
protected:
  T data;
};

template <class T>
class OtherDependent : public Dependent<T>
{
public:
  void printT()const
  { 
    std::cout << "T: " << data << std::endl; //ERROR
  }
};

int main()
{
  OtherDependent<int> o;
  o.printT();
  return 0;
}

发生此错误是因为编译器不会在基类模板中查找名称 data,因为它不依赖于 T,因此它不是依赖项姓名。修复的方法是使用 this 或显式告诉依赖的基类模板:

std::cout << "T: " << this->data << std::endl; //Ok now.
std::cout << "T: " << Dependent<T>::data << std::endl; //Ok now.

或放置使用声明:

template <class T>
class OtherDependent : public Dependent<T>
{
    using Dependent<T>::data; //Ok now.
    ....
};

关于c++ - 如何理解 C++ 中的依赖名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1527849/

相关文章:

c++ - Linux 终端管道到我的 C++ 程序

c++ - 什么是适用于 C 或 C++ 的良好 MySQL 库?

c++ - 在没有标题的c++ dll中调用函数

c++ - start_thread 克隆在并行程序中占用了大部分时间 - 并行化错误或报告错误?

c++ - Irrlicht:如何在场景管理器中启用所有节点的阴影?

C++ 迭代结构

c++ - 总是使用构造函数而不是显式转换运算符

c++ - 显示正交的 OpenGL 投影矩阵

c++ - 对 `std::thread::_M_start_thread CMake 的基准 undefined reference

C++ 重载运算符 << 以处理指针 vector