TemplateSpecialization

Template Specialization – More Details About Class Templates

After I presented in my last post Template Specialization, the basics about template specialization, I dig deeper today. I want to present the partial and full specialization of a class template as a compile-time if.

TemplateSpecialization

Specialization of Class Templates as a Compile-Time if

After my last blog post Template Specialization, I got a few similar questions. How can you decide if a type is a given type or if two are the same? Answering these questions is easier and helps me present more theories about class template specialization. To answer these questions, I implement simplified versions of std::is_same , and std::remove_reference. The presented techniques in this post apply class template specialization and are a compile-time if.

std::is_same

std::is_same is a function from the type-traits library. It returns std::true_type if both types are the same, otherwise, it returns std::false_type. For simplicity reasons, I return true or false.

// isSame.cpp

#include <iostream>

template<typename T, typename U>                 // (1)
struct isSame {
    static constexpr bool value = false;
};
 
template<typename T>                             // (2)
struct isSame<T, T> {
    static constexpr bool value = true;
}; 

int main() {

    std::cout << '\n';                          

    std::cout << std::boolalpha;
                                                // (3)
    std::cout << "isSame<int, int>::value: " << isSame<int, int>::value << '\n';
    std::cout << "isSame<int, int&>::value: " << isSame<int, int&>::value << '\n';
  
                                                
    int a(2011);
    int& b(a);                                  // (4)
    std::cout << "isSame<decltype(a), decltype(b)>::value " << 
                  isSame<decltype(a), decltype(b)>::value << '\n';

    std::cout << '\n';

}

 

The primary template (1) returns as the default false, when you ask for its value. On the contrary, the partial specialization (2) that is used when both types are the same returns true. You can use the class template isSame on types (3) and, thanks to decltype, on values (4). The following screenshot shows the output of the program.

isSame

You may already guess it. The class template isSame is an example of template metaprogramming. Now, I have to make a short detour and write a few meta words.

Rainer D 6 P2 500x500

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    Metafunctions and Metadata

    At runtime, we use data and functions. At compile time, we use metadata and metafunctions. Quite easy, it’s called meta because we do metaprogramming, but what is metadata or a metafunction? Here is the first definition.

    • Metadata: Types and integral values that are used in metafunctions.
    • Metafunction: Functions that are executed at a compile time.

    Let me elaborate more on the terms metadata and metafunction.

    Metadata

    Metadata includes three entities:

    1. Types such as int, double, or std::string
    2. Non-types such as integrals, enumerators, pointers, lvalue reference, and floating-point values with C++20
    3. Templates

    So far, I have only used types in my metafunction isSame.

    Metafunction

    Types such as the class template isSame are used in template metaprogramming to simulate functions. Based on my definition of metafunctions, constexpr functions can also be executed at compile time and are, therefore, metafunctions.

    A metafunction cannot only return a value, but it can also return a type. By convention, a metafunction returns a using via ::value, and a type using ::type.The following metafunction removeReference returns a type as a result.

    // removeReference.cpp
    
    #include <iostream>
    #include <utility>
    
    template<typename T, typename U>                 
    struct isSame {
        static constexpr bool value = false;
    };
     
    template<typename T>                             
    struct isSame<T, T> {
        static constexpr bool value = true;
    }; 
    
    template<typename T>                // (1)
    struct removeReference { 
        using type = T;
    };
    
    template<typename T>               // (2)
    struct removeReference<T&> {
        using type = T;
    };
    
    template<typename T>               // (3)
    struct removeReference<T&&> {
        using type = T;
    };
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << std::boolalpha;
                                        // (4)                
        std::cout << "isSame<int, removeReference<int>::type>::value: " << 
                      isSame<int, removeReference<int>::type>::value << '\n';
    
        std::cout << "isSame<int, removeReference<int&>::type>::value: " << 
                      isSame<int, removeReference<int&>::type>::value << '\n';
    
        std::cout << "isSame<int, removeReference<int&&>::type>::value: " << 
                      isSame<int, removeReference<int&&>::type>::value << '\n';
    
    
                                      // (5)
    
        int a(2011);
        int& b(a);   
        std::cout << "isSame<int, removeReference<decltype(a)>::type>::value: " << 
                      isSame<int, removeReference<decltype(a)>::type>::value << '\n';
    
        std::cout << "isSame<int, removeReference<decltype(b)>::type>::value: " << 
                      isSame<int, removeReference<decltype(b)>::type>::value << '\n';
    
        std::cout << "isSame<int, removeReference<decltype(std::move(a))>::type>::value: " << 
                      isSame<int, removeReference<decltype(std::move(a))>::type>::value << '\n';
    
        std::cout << '\n';
    
    }
    

     

    In this example, I apply the previously defined metafunction isSame and the metafunction removeReference. The primary template removeReference (1) returns T using the name type. The partial specializations for the lvalue reference (2) and the rvalue reference also return T by removing the references from its template parameter. As before, you can use the metafunction removeReference with types (4) and, thanks to decltype, with values (5). decltype(a) returns a value, decltype(b) an lvalue reference, and an rvalue reference.

    Finally, here is the output of the program.

    removeReference

    There is one trap I fall into. When you define a member function of a fully specialized class template outside the class, you must not use template<>.

    Member Functions of Specialization Defined Outside the Class Body

    The following code program shows the class template Matrix, having a partial and a full specialization.

     

    // specializationExtern.cpp
    
    #include <cstddef>
    #include <iostream>
    
    template <typename T, std::size_t Line, std::size_t Column>  // (1)
    struct Matrix;
    
    template <typename T>                                        // (2)
    struct Matrix<T, 3, 3>{
        int numberOfElements() const;
    };
    
    template <typename T>
    int Matrix<T, 3, 3>::numberOfElements() const {
        return 3 * 3;
    };
    
    template <>                                                 // (3)
    struct Matrix<int, 4, 4>{
        int numberOfElements() const;
    };
    
    // template <>                                              // (4)
    int Matrix<int, 4, 4>::numberOfElements() const {
        return 4 * 4;
    };
    
    int main() {
    
        std::cout << '\n';
    
        Matrix<double, 3, 3> mat1;                              // (5)
        std::cout << "mat1.numberOfElements(): " << mat1.numberOfElements() << '\n';
    
        Matrix<int, 4, 4> mat2;                                 // (6)
        std::cout << "mat2.numberOfElements(): " << mat2.numberOfElements() << '\n';
    
        std::cout << '\n';
        
    }
    

     

    (1) declares the primary template. (2) defines the partial specialization, and (3) the full specialization of Matrix. The member functions numberOfElements are defined outside the class body. Line (4) is probably the non-intuitive line. When you define the member function numberOfElements outside the class body, you must not use template <>. Line (5) causes the instantiation of the partial, and line (6) causes the instantiation of the full specialization.

    specializationExtern

    What’s next?

    In my next post, I will write about the full specialization of function templates and their surprising interplay with functions. To make a long story short, according to the C++ Core Guidelines holds: T.144: Don’t specialize function templates.

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *