WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Advanced · question 45 of 100

What is the difference between ’typename’ and ’class’ in C++ template declarations?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

In C++ template declarations, ’typename’ and ’class’ are used interchangeably to specify a type parameter. Both keywords allow you to define a template class or function that can work with different types.

However, there is a subtle difference between the two keywords when it comes to dependent types. A dependent type is a type that depends on a template parameter and cannot be resolved until the template is instantiated.

When using a dependent type in a template declaration, you must use the ’typename’ keyword instead of ’class’. This is because the compiler cannot determine whether a dependent name refers to a type or a non-type until it sees the template arguments. By using the ’typename’ keyword, you tell the compiler that the name refers to a type.

Here is an example that demonstrates the use of the ’typename’ keyword in a template declaration:

    template<typename T>
    class MyClass {
        public:
        typename T::iterator begin();
        typename T::iterator end();
        
        private:
        T m_data;
    };
    
    template<typename T>
    typename T::iterator MyClass<T>::begin() {
        return m_data.begin();
    }
    
    template<typename T>
    typename T::iterator MyClass<T>::end() {
        return m_data.end();
    }

In this example, the ’typename’ keyword is used to declare the return type of the ’begin()’ and ’end()’ member functions. The return type is a dependent type that depends on the type parameter ’T’, so the ’typename’ keyword is required to tell the compiler that ’T::iterator’ is a type.

Note that if you use the ’class’ keyword instead of ’typename’ in this example, you will get a compilation error.

Overall, the ’typename’ and ’class’ keywords are mostly interchangeable in C++ template declarations, but you should use ’typename’ when working with dependent types to avoid compilation errors.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics