AutomaticReturnType

Automatic Return Type (C++11/14/20)

I started my discussion about the  “Automatic Return Type (C++98)” in my last post. Today, I’m faced with the same challenge but solve it with C++11, C++14, and C++20.

 AutomaticReturnType

To remind you: Here is the challenge I want to solve.

template <typename T, typename T2>
??? sum(T t, T2 t2) {
    return t + t2;
}

 

When you have a function template with at least two type parameters, you can not decide in general the return type of the function. Of course, sum should return the type the arithmetic operation t + t2 returns.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    std::cout << typeid(5.5 + 5.5).name();    // double
    std::cout << typeid(5.5 + true).name();   // double
    std::cout << typeid(true + 5.5).name();   // double
    std::cout << typeid(true + false).name(); // int
    

     

    When you want to read the full story, read my previous post “Automatic Return Type (C++98)“. Now, I jump to C++11.

    C++11

    In C++11, there are essentially two ways to solve this issue: type-traits or auto combination with decltype.

    Type-Traits

    The Type-traits library has the function std::common_type. This function determines at compile time the common type of an arbitrary number of types. The common type is that type among all types to which all types can be implicitly converted. If this type is not available, you get a compile-time error.

     

    // automaticReturnTypeTypeTraits.cpp
    
    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    
    template <typename T, typename T2>
    typename std::common_type<T, T2>::type sum(T t, T2 t2) {
        return t + t2;
    }
    
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << typeid(sum(5.5, 5.5)).name() << '\n';     // double
        std::cout << typeid(sum(5.5, true)).name() << '\n';    // double
        std::cout << typeid(sum(true, 5.5)).name() << '\n';    // double
        std::cout << typeid(sum(true, false)).name() << '\n';  // bool
    
        std::cout << '\n';
    
    }
    

     

    For simplicity reasons, I display the string representation of the type in the source code. I used the MSVC compiler. The GCC or Clang compiler would return single characters such as d for double and b for bool.

    There is one subtle difference between std::common_type and all other variants I presented in the last post and this post: std::common_type returns the common type, but my traits solution in the last post, “Automatic Return Type (C++98)“, and the solutions based on auto in this post returns the type to which the expression t + t2 evaluates to.

    auto in Combination with decltype

    Using auto to deduce the return type of a function in C++11 is way too verbose.

    First, you have to use the so-called trailing return type, and second, you have to specify the return type in a decltype expression.

     

    // automaticReturnTypeTypeAutoDecltype.cpp
    
    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    
    template <typename T, typename T2>
    auto sum(T t, T2 t2) -> decltype(t + t2) {
        return t + t2;
    }
    
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << typeid(sum(5.5, 5.5)).name() << '\n';     // double
        std::cout << typeid(sum(5.5, true)).name() << '\n';    // double
        std::cout << typeid(sum(true, 5.5)).name() << '\n';    // double
        std::cout << typeid(sum(true, false)).name() << '\n';  // int
    
        std::cout << '\n';
    
    }
    

     

     You have to read the expression auto sum(T t, T2 t2)  -> decltype(t + t2) in the following way. You express with auto that you don’t know the type and promise that you specify the type later. This specification happens in the decltype expression: decltype(t + t2). The return type of the function template sum is that type to which the arithmetic expression evaluates. Here is what I don’t like about this C++11 syntax: You have to use two times the same expression t + t2. This is error-prone and redundant. The trailing return type syntax is in general optional but required for automatic return type deduction in C++11 and lambdas.

    Let’s see if C++14 simplifies the use of the automatic return type.

    C++14

    With C++14, we got the convenient syntax for automatic return type deduction without redundancy.

    // automaticReturnTypeTypeAuto.cpp
    
    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    
    template <typename T, typename T2>
    auto sum(T t, T2 t2) {
        return t + t2;
    }
    
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << typeid(sum(5.5, 5.5)).name() << '\n';     // double
        std::cout << typeid(sum(5.5, true)).name() << '\n';    // double
        std::cout << typeid(sum(true, 5.5)).name() << '\n';    // double
        std::cout << typeid(sum(true, false)).name() << '\n';  // int
    
        std::cout << '\n';
    
    }
    

     

    In C++14, you can just use auto as a return type.

    Let’s make the last jump to C++20.

    C++20

    In C++20, you should use instead of an unconstrained placeholder a constrained placeholder, aka concept. Defining and using the concept Arithmetic expresses explicitly my intent. Only arithmetic types are allowed in the function template sum.

    // automaticReturnTypeTypeConcepts.cpp
    
    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    
    template<typename T>
    concept Arithmetic = std::is_arithmetic<T>::value;
    
    Arithmetic auto sum(Arithmetic auto t, Arithmetic auto t2) {
        return t + t2;
    }
    
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << typeid(sum(5.5, 5.5)).name() << '\n';     // double
        std::cout << typeid(sum(5.5, true)).name() << '\n';    // double
        std::cout << typeid(sum(true, 5.5)).name() << '\n';    // double
        std::cout << typeid(sum(true, false)).name() << '\n';  // int
    
        std::cout << '\n';
    
    }
    

     

    I’m defining the concept Arithmetic by directly using the type-traits function std::is_arithmetic. The function std::is_arithmetic is a so-called compile-time predicate. A compile-time function is a function that returns at compile-time a boolean.

    If you want to read more about concepts, read my previous posts about concepts.

    What’s next?

    Template metaprogramming, or programming at compile time using templates, is a potent C++ technique with a bad reputation. The functions of the type-traits library, such as std::common_type or std::is_arithmetic are examples of template metaprogramming in C++. In my next post, I will elaborate more on template metaprogramming.

    C++20 Training for Meeting C++

    Next Tuesday (02.11.2021), I will give a one-day training about the big four in C++20 (Concepts, Ranges, Modules, and Coroutines). You will also get a coupon for my C++20 book when you book my training.

     

    I’m happy to see you,

    RainerGrimmSmall

     

     

     

     

     

    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, Kris Kafka, 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, Dmitry Farberov, 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, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    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

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    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 *