0

This is the bind2nd definition:

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

And the key word typename can be used to:

  • In a template declaration, typename can be used as an alternative to class to declare type template parameters.

  • Inside a declaration or a definition of a template, typename can be used to declare that a dependent name is a type.

So, I think typename is used to declare that Operation::second_argument_type is a type, but I want to know why we need to use typename here ?Can't we use it ? What is the advantage to use it ?

karllo
  • 341
  • 3
  • 10
  • It won't work without `typename`. The purpose is just to allow the compiler to do a few more checks on the template, and perhaps prepare a representation of the content that's able to be instantiated faster later when actual use of the template is made. – Tony Delroy Apr 03 '14 at 09:08
  • "So, I think typename *is used to declare that Operation::second_argument_type is a type*, but *I want to know why we need to use typename* here ? *Can't we use it ?*" What do you mean? – Rubens Apr 03 '14 at 09:10
  • 1
    @Rubens because I think whether there is a declaration or not , Operation::second_argument_type is a type. – karllo Apr 03 '14 at 09:47

1 Answers1

0

C++ syntax depends on whether identifier is a type or not. A statement can't be parsed without that knowledge.

Normally the compiler just looks whether the identifier has been declared as type or not. However if the symbol is dependent on template parameter, the compiler can't look. So you have to tell it.

If you use

Operation::second_argument_type

and it is a type, the compilation will fail, because the template will already be parsed assuming it is an object and if you use

typename Operation::second_argument_type

and it is not a type, the compilation will fail, because the template will already be parsed assuming it is a type.

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172