Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

Similar documents
Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019

Modern C++, From the Beginning to the Middle. Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017

Undefined Behavior is Not an Error. Barbara Geller & Ansel Sermersheim C++ London 2019

Undefined Behavior is Not an Error. Barbara Geller & Ansel Sermersheim CppCon - Sept 2018

Multithreading Using Lockless Lists and RCU. Ansel Sermersheim CppNow - May 2017

CopperSpice: A Pure C++ GUI Library. Barbara Geller & Ansel Sermersheim CPPCon - September 2015

CopperSpice and the Next Generation of Signals. Barbara Geller & Ansel Sermersheim CppNow - May 2016

A Taxonomy of Expression Value Categories

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Rvalue References as Funny Lvalues

Value categories. PRvalues. Lvalues

Basic Types, Variables, Literals, Constants

Axivion Bauhaus Suite Technical Factsheet AUTOSAR

Tokens, Expressions and Control Structures

Operator Dot Wording

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

Multithreading is the answer. What is the question? Ansel Sermersheim & Barbara Geller ACCU / C++ January 2018

Introduction to Move Semantics in C++ C and C

Using Enum Structs as Bitfields

CS93SI Handout 04 Spring 2006 Apr Review Answers

C++11 and Compiler Update

OBJECT ORIENTED PROGRAMMING USING C++

Explicit Conversion Operator Draft Working Paper

Introduction to Core C++

Part X. Advanced C ++

IBM i Version 7.3. Programming IBM Rational Development Studio for i ILE C/C++ Language Reference IBM SC

use static size for this buffer

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced

Structured bindings with polymorphic lambas

C The new standard

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CS

Elevate your Code to Modern C++ with Automated Tooling. Peter Sommerlad

CS201 - Introduction to Programming Glossary By

C++ Functions. Procedural-based Programming. what s a functions

IBM i Version 7.2. Programming IBM Rational Development Studio for i ILE C/C++ Language Reference IBM SC

template <typename T> // unless it s an unqualified pointer struct IsPtr<T *> { enum { r = true }; };

Multithreading is the answer. What is the question? (part 1)

New wording for C++0x Lambdas

Intermediate C++ 1/83

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

AIMS Embedded Systems Programming MT 2017

Introduce C# as Object Oriented programming language. Explain, tokens,

Short Notes of CS201

Chapter 2. Procedural Programming

Compiler Construction I

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Introduction to C++11 and its use inside Qt

Database Systems on Modern CPU Architectures

Variables. Data Types.

CS11 Advanced C++ Fall Lecture 7

Rvalue References, Move Semantics, Universal References

Appendix A Cg Language Specification

Generalized lifetime extension!

Axivion Bauhaus Suite Technical Factsheet MISRA

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

TDDD38 - Advanced programming in C++

EXP54-CPP. Do not access an object outside of its lifetime

C++ Coding Standards. 101 Rules, Guidelines, and Best Practices. Herb Sutter Andrei Alexandrescu. Boston. 'Y.'YAddison-Wesley

QUIZ. What is wrong with this code that uses default arguments?

1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)

Introduction to C++ with content from

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Rvalue References & Move Semantics

P1267R0: Custom Constraint Diagnostics

Instantiation of Template class

Outline. 1 About the course

Advanced C++ Topics. Alexander Warg, 2017

Introduction to Standard C++

Chapter 1 Getting Started

Operator Dot Wording

Generalized pointer casts

C++11/14 Rocks. Clang Edition. Alex Korban

10. Functions (Part 2)

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

Type Conversion. and. Statements

Generalized Constant Expressions

Advanced Systems Programming

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Decltype (revision 6): proposed wording

Absolute C++ Walter Savitch

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

Introduction to Programming Using Java (98-388)

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

CSCI-1200 Data Structures Fall 2018 Lecture 21 Hash Tables, part 1

G52CPP C++ Programming Lecture 15

I m sure you have been annoyed at least once by having to type out types like this:

Programming in C and C++

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Programming in C++ Indian Institute of Technology, Kharagpur

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus

Cg_language(Cg) Cg Language Specification Cg_language(Cg)

CS3157: Advanced Programming. Outline

September 10,

Qualified std::function signatures

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

C++ Modern and Lucid C++ for Professional Programmers

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Templates Templates are functions or classes that are parameterized. We have already seen a few in STL:

Transcription:

Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1

Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences Examples Bonus Round 2

Definitions Function Overloading function overloading pertains to free functions, constructors, and methods developers commonly refer to all of these as functions the order of declaration for overloaded functions is not meaningful two or more functions are overloads of each other when they have the exact same function name are visible from the same scope have a different set of parameters 3

Definitions When is a Function Overload an Error two functions which differ only by the return type will not compile since you do not have to use the return value it looks like the same function is defined twice two functions which differ only in their default arguments will not compile default values do not make the function signature different two methods with the same name and parameters where one method is declared static will not compile, ambiguous 4

Example Example 1 void dothing1(int) // overload 1 { void dothing1(int, double) // overload 2 { int main() { dothing1(42); // calls overload 1 dothing1(42, 3.14); // calls overload 2 5

Determining which overload to call which overload to call is computed by the compiler in simple cases this process is intuitive and usually results in calling the expected overload however, it can get complicated very fast pointer and reference data types do not always resolve as you might initially expect template functions can deduce arguments in unexpected ways overload resolution is the name of the process in C++ for selecting which overload function is called C++17 standard defines overload resolution in clause 16 6

What is Overload Resolution process used to select the most appropriate overload of a function during this process the compiler must decide which overload to call done at compile time only considers argument data types and how they match the parameter data types, never the values which are passed if the compiler can not choose one specific function, the function call is considered ambiguous template functions or methods they participate in the overload resolution process if two overloads are deemed equal, a non-template function will always be preferred over a template function 7

Before Overload Resolution compiler must first perform what is called name lookup in order to compile a function call name lookup is the process of finding every function declaration which is visible from the current scope name lookup may require argument-dependent lookup template functions may require template argument deduction 8

Details of Overload Resolution first step is for all overloads to be put in a list of candidates template argument deduction is done just prior to creating the candidate list or while it is being created the next step is to remove any invalid candidates according to the C++ standard functions which are invalid are regarded as not viable what makes a particular candidate invalid passed argument count does not match the parameter list passing fewer arguments than the function parameter list declared may still be a valid overload if default arguments exist passed arguments are not a possible match even considering implicit conversions 9

Type Conversions also known as type casting and type coercion a way of changing a value of one data type into another type int to a float string literal to a pointer enum to an int timestamp to a long int to a string char * to a void * std::any to std::vector ( or anything ) 10

Type Conversions type conversions are either implicit or explicit example of an implicit conversion char foo[] = "ABC"; int bar = foo[0]; // bar will equal 65 an explicit conversion would be a static_cast, dynamic_cast, reinterpret_cast, c style cast another type of explicit conversion is a functional cast if (std::string( root ) == current_directory) { // do something 11

Type Conversion other considerations regarding type conversion whether the original type is converted to another type data in memory is actually changed to a different format int var1 = 5; float var2 = var1; original representation is reinterpreted as another type data in memory does not change, just looking at it differently float var3 = 8.17; const char * var4 = reinterpret_cast<const char *>(&var3); 12

Standard Conversion Sequences - Order of Ranking exact match no conversion is required lvalue transformations lvalue to rvalue conversion array to pointer conversion function to pointer conversion qualification adjustments qualification conversion function pointer conversion ( new in C++17 ) 13

Standard Conversion Sequences - Order of Ranking numeric promotions integral promotion floating-point promotion conversions integral conversion floating-point conversion floating integral conversion pointer conversion pointer-to-member conversion boolean conversion 14

LValue to RValue Conversion based on value categories according to the C++ standard a glvalue of any non-function, non-array type T can be implicitly converted to a prvalue of the same type if T is a non-class type, this conversion also removes cv-qualifiers parameter which expects an rvalue and is passed an lvalue 15

Qualification Conversion according to the C++ standard prvalue of type pointer to T can be converted to a prvalue of type pointer to more cv-qualified T constness and volatility can be added to a pointer this is an implicit extra first parameter to a member function allows a const or volatile qualified member function to be a candidate for a call which passed an unqualified object std::vector<int> data; data.size(); // data is not const, size() method is const qualified 16

Example 2 void dothing2(char value) // overload 1 { void dothing2(long value) // overload 2 { int main() { dothing2(42); // which overload is called? 17

Example 2 void dothing2(char value) // overload 1 { void dothing2(long value) // overload 2 { int main() { dothing2(42); // ambiguous ( compile error ) 18

Argument Conversions standard conversion - integral promotion unsigned short promotable to unsigned int or int depends on your platform short promotable to int char promotable to int or unsigned int depends on your platform bool promotable to int (0 or 1) standard conversion - floating point promotion float to double 19

Example 3 integral conversion from an int to a long void count(long value) { // candidate int main() { count(42); 20

Example 4 compile error message - no matching function for call to compile output lists one candidate void dothing4(char x1) { // no overload int main() { dothing4( x, nullptr); 21

User Defined Conversions standard conversions are part of C++ part of the language, used to convert between the known types implicit conversions in the STL are considered user defined classes in the STL like std::string, std::shared_ptr, etc const_iterators are implicitly convertible to iterators C++ has no knowledge about conversions between user defined data types which are defined in your classes or application all user defined conversions have a lower ranking below the standard conversions 22

Example 5 void dothing5(char value) { template <typename T> void dothing5(t value) { // candidate A // candidate B int main() { dothing5(42); // which overload is called? 23

Example 5 void dothing5(char value) { template <typename T> void dothing5(t value) { // candidate A // candidate B int main() { dothing5(42); // candidate B wins 24

Best Overload Selection if only one function is better than all other functions in the candidate list, it is called the best viable function and is selected by the overload resolution process create the candidate list remove the invalid functions rank the candidates process of ranking the remaining candidates is how the compiler finds the single best match best candidate match may be the least bad match tie breakers 25

Pick a Candidate tie breakers are used throughout overload resolution to decipher which candidate might be a better match when a template and a non-template candidate are tied for first place the non-template function is selected an implicit conversion which requires fewer steps is a better match than a candidate which takes more steps if there is no best match or there is an unresolvable tie, a compiler error is generated 26

Ranking Candidates exact match no conversion, lvalue to rvalue, cv qualification numeric promotion integral, floating point conversion integral, floating point, pointer, boolean user defined conversion convert a const char * to an std::string ellipsis conversion c style varargs function call 27

Candidate List has no best Match compile error saying something like call of overloaded some function name is ambiguous followed by a list of possible candidates how to resolve this compiler error change your overload set mark a constructor explicit to prevent an implicit conversion template functions can be eliminated through SFINAE a template function which is not instantiated will not be placed in the candidate set 28

Candidate List has no best Match convert the arguments before the call explicit conversions static_cast<> an argument being passed explicitly construct an object use std::string( some text ) rather than pass a string literal 29

Complications overload resolution is really hard to debug since there is no clean way to ask the compiler why it chose a particular overload overload resolution can be more complex than template argument deduction given a template function with a template parameter T where one of the parameters is const T& this function will be an exact match for nearly every call which may not be what you intended 30

Example 6 CsString library has a constructor which allows a const char * or char * to be implicitly converted to a CsString CsString has a #define if enabled this will cause a static_assert in this constructor thus causing a compiler error and disallowing the conversion #define CS_STRING_ALLOW_UNSAFE template <typename T, typename = typename std::enable_if<std::is_same<t, const char *>::value std::is_same<t, char *>::value>::type> CsBasicString(const T &str, const A &a = A()); 31

Example 6 constructor implementation template <typename E, typename A> template <typename T, typename> CsBasicString<E, A>::CsBasicString(const T &str, const A &a) : m_string(1, 0, a) { #ifndef CS_STRING_ALLOW_UNSAFE static_assert(! std::is_same<e, E>::value, "Unsafe operation not..."); #endif // constructor implementation source removed for simplicity 32

Example 6 CsString library has the #define enabled in this example str will be implicitly converted to a CsString void dothing6(csstring value) { int main() { const char *str = spring is here ; dothing6(data); 33

Example 7 // A void dothing_a(double, int, int) { // overload 1 void dothing_a(int, double, double) { // overload 2 int main() { dothing_a(4, 5, 6); // which overload is called? // B void dothing_b(int, int, double) { // overload 3 void dothing_b(int, double, double) { // overload 4 int main() { dothing_b(4, 5, 6); // which overload is called? 34

Example 7 // A void dothing_a(double, int, int) { // overload 1 void dothing_a(int, double, double) { // overload 2 int main() { dothing_a(4, 5, 6); // ambiguous ( compile error ) // B void dothing_b(int, int, double) { // overload 3 void dothing_b(int, double, double) { // overload 4 int main() { dothing_b(4, 5, 6); // overload 3 wins 35

Example 8 // A void dothing_d(int &) { // overload 1 void dothing_d(int) { // overload 2 int main() { int x = 42; dothing_d(x); // which overload is called? // B void dothing_e(int &) { // overload 3 void dothing_e(int) { // overload 4 int main() { dothing_e(42); // which overload is called? 36

Example 8 // A void dothing_d(int &) { // overload 1 void dothing_d(int) { // overload 2 int main() { int x = 42; dothing_d(x); // ambiguous ( compile error ) // B void dothing_e(int &) { // overload 3 void dothing_e(int) { // overload 4 int main() { dothing_e(42); // overload 4 wins 37

Example 9 // A void dothing_f(int &) { // overload 1 void dothing_f(int &&) { // overload 2 int main() { int x = 42; dothing_f(x); // which overload is called? // B void dothing_g(int &) { // overload 3 void dothing_g(int &&) { // overload 4 int main() { dothing_g(42); // which overload is called? 38

Example 9 // A void dothing_f(int &) { // overload 1 void dothing_f(int &&) { // overload 2 int main() { int x = 42; dothing_f(x); // overload 1 wins // B void dothing_g(int &) { // overload 3 void dothing_g(int &&) { // overload 4 int main() { dothing_g(42); // overload 4 wins 39

Example 10 - Bonus Round void dothing_c(int &) { // overload 1, lvalue ref to int void dothing_c(...) { // overload 2, c style varargs struct MyStruct { int m_data : 5; ; // bitfield, 5 bits stored in an int int main() { MyStruct object; dothing_c(object.m_data); // which overload is called? 40

Example 10 - Bonus Round void dothing_c(int &) { // overload 1, lvalue ref to int void dothing_c(...) { // overload 2, c style varargs struct MyStruct { int m_data : 5; ; // bitfield, 5 bits stored in an int int main() { MyStruct object; dothing_c(object.m_data); // overload 1 wins Hang on, compile error non const reference can not bind to bit field adding an overload which takes a const int & does not change the result 41

Presentations Why CopperSpice Why DoxyPress Compile Time Counter Modern C++ Data Types (references) Modern C++ Data Types (value categories) Modern C++ Data Types (move semantics) CsString library (unicode) CsString library (library design ) Multithreading in C++ Multithreading using libguarded Signals and Slots Build Systems Templates in the Real World Copyright Copyleft What s in a Container Modern C++ Threads C++ Undefined Behavior Regular Expressions Using DoxyPress Type Traits C++ Tapas (typedef, forward declarations) Lambdas in C++ C++ Tapas (typename, virtual, pure virtual) Overload Resolution Next video available on June 14 Please subscribe to our YouTube Channel https://www.youtube.com/copperspice 42

Libraries CopperSpice libraries for developing GUI applications CsSignal Library standalone thread aware signal / slot library CsString Library standalone unicode aware string library libguarded standalone multithreading library for shared data 43

Applications KitchenSink one program which contains 30 demos links with almost every CopperSpice library Diamond programmers editor which uses the CopperSpice libraries DoxyPress & DoxyPressApp application for generating source code and API documentation 44

Where to find CopperSpice www.copperspice.com ansel@copperspice.com barbara@copperspice.com source, binaries, documentation files download.copperspice.com source code repository github.com/copperspice discussion forum.copperspice.com 45