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

Contents[Show]

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.

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 be 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 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.

In case 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 very powerful 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 elaborate more on template metaprogramming.

C++20 Training for Meeting C++

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

 

I'm happy to see you,

RainerGrimmSmall

 

 

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Haken Gedek, and Bernd Mühlhaus.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, and Rusty Fleming.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

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

Bookable (Online)

German

Standard Seminars (English/German)

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

New

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 7570

Yesterday 5977

Week 7570

Month 40948

All 8160094

Currently are 231 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments