Search code examples
c++headertypedeftypename

can we use the C++ keyword "typename" without templates?


I saw this code in a header file.

using pointIndex = typename std::pair<std::vector<double>, size_t>;
  1. Can we use "typename" here without a template?
  2. Is it necessary to use typename here?
  3. What is the difference between "typedef" and "typename"?

Solution

  • typename and typedef are completely different things.

    typedef is a keyword used to introduce a type alias (a type definition). In recent standards you can also use using for this. So:

    typedef int MyThing;
    
    // or
    using MyThing = int;
    

    typename is a keyword that says "the next thing is a type". It's used when dealing with templates in some situations, both in template declarations (e.g. template <typename T> void foo() { /*..*/ }) and to help the parser along in some situations. In the example you've given, it is valid, but redundant.

    The two things are entirely different, and thus not interchangeable.