为什么在"typename Operation::second_argument_type(x)"中使用typename?

Why does it use typename in "typename Operation::second_argument_type(x)"?

本文关键字:typename argument Operation second 为什么 type      更新时间:2023-10-16

这是绑定的第二个定义:

 template <class Operation, class T>
    binder2nd<Operation> bind2nd (const Operation& op, const T& x)
    {
      return binder2nd<Operation>(op, typename Operation::second_argument_type(x));
    }

关键字类型名称可用于:

  • 在模板声明中,类型名可以用作用于声明类型模板参数的类。

  • 在模板的声明或定义中,类型名可以是用于声明依赖名称是一个类型。

所以,我认为typename用于声明Operation::second_argument_type是一种类型,但我想知道为什么我们需要在这里使用typename?我们不能使用它吗?使用它有什么好处?

C++语法取决于标识符是否是一种类型。如果没有该知识,则无法解析语句。

通常,编译器只查看标识符是否已声明为类型。但是,如果符号依赖于模板参数,则编译器无法查看。所以你必须告诉它。

如果您使用

Operation::second_argument_type

它是一种类型,编译将失败,因为假设它是一个对象并且如果您使用

typename Operation::second_argument_type

它不是一个类型,编译将失败,因为假设它是一个类型,模板已经被解析了。

相关文章: