Site Tools


wiki:cpp-dependent-names

Table of Contents

C++ Dependent names

Dependent names are names in template code that depend on template parameters. When a dependent name is ambiguous (could be a type or value), the compiler assumes it's a value unless declared with typename. Writing typename T::value_type tells the compiler that value_type is a type member of T.

Qualify dependent type names with typename; this is required by the standard and aids readability.

Example

This example shows dependent name disambiguation with typename keyword.

// compile: g++ -std=c++17 -o dependent dependent.cpp
// run: ./dependent
// description: dependent names require typename for type members
 
#include <iostream>
#include <vector>
#include <type_traits>
 
template <typename T>
void process(T& container) {
    // Without typename, compiler doesn't know this is a type
    typename T::value_type value = container.at(0);
 
    std::cout << "Value: " << value << "\n";
}
 
template <typename T>
struct Traits {
    // This typedef is a dependent type
    using type = T;
};
 
template <typename T>
void use_traits() {
    typename Traits<T>::type value{};
    std::cout << "Trait type used\n";
}
 
int main() {
    std::vector<int> v{42};
    process(v);
 
    use_traits<int>();
 
    return 0;
}
wiki/cpp-dependent-names.md · Last modified: (external edit)