Implicit Evaluation of auto Variables and Arguments

Similar documents
Implicit Evaluation of auto Variables and Arguments

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

Class Types in Non-Type Template Parameters

American National Standards Institute Reply to: Josee Lajoie

Type Inference auto for Note: Note:

Let return Be Direct and explicit

Wording for lambdas in unevaluated contexts

Lambda Correctness and Usability Issues

Rvalue References as Funny Lvalues

Qualified std::function signatures

C++11 and Compiler Update

Class Types in Non-Type Template Parameters

New wording for C++0x Lambdas

register lock_guard(mtx_); string_view s = register to_string(42); We propose register-expression to grant the temporary objects scope lifetimes.

Class Types in Non-Type Template Parameters

Deducing the type of variable from its initializer expression (revision 4)

Generalized Constant Expressions

Deducing the type of variable from its initializer expression (revision 3)

The Syntax of auto Declarations

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Deducing the type of variable from its initializer expression Programming Language C++ Document no: N1721=

Class Types in Non-Type Template Parameters

Allowing Class Template Specializations in Associated Namespaces (revision 1)

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

C The new standard

Botet C++ generic overload functions P0051

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

Doc. No.: WG21/N0937=X3J16/ Date: 28 May 1996 Project: C++ Standard Library Reply to: Nathan Myers

Template Issue Resolutions from the Stockholm Meeting

Expansion statements. Version history. Introduction. Basic usage

Technical Specification: Concepts

CPSC 427a: Object-Oriented Programming

Structured bindings with polymorphic lambas

A Proposal to Add a Const-Propagating Wrapper to the Standard Library

More Improvements to std::future<t> - Revision 1

std::optional from Scratch

An Alternative to Name Injection from Templates

Tokens, Expressions and Control Structures

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

On the Coroutines TS

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Variant: a type-safe union without undefined behavior (v2).

A Taxonomy of Expression Value Categories

Simplifying C++0x Concepts

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

Lambdas in unevaluated contexts

Chapter 7 Constructors and Other Tools. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CPSC 427: Object-Oriented Programming

Botet C++ generic match function P0050

Working Draft, C++ Extensions for Concepts

Instantiation of Template class

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

SFU CMPT Topic: Class Templates

Operator Dot Wording

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

Innovative Produktentwicklung durch

C++ Important Questions with Answers

Advanced C++ Topics. Alexander Warg, 2017

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

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions

Making operator?: overloadable

simd<t> Finding the right set of traits for Document Number: P0964R1 Date: Matthias Kretz Target: Parallelism TS 2

The C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1)

Chapter 7. Constructors and Other Tools. Copyright 2016 Pearson, Inc. All rights reserved.

Part X. Advanced C ++

Lambdas in unevaluated contexts

P1267R0: Custom Constraint Diagnostics

Working Draft, Extensions to C++ for Modules

Abstract This paper proposes the ability to declare multiple variables initialized from a tuple or struct, along the lines of:

Object-Oriented Principles and Practice / C++

Abstract This paper proposes the ability to declare multiple variables initialized from a tuple or struct, along the lines of:

Extended friend Declarations

Proposed Wording for Variadic Templates

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

A Proposal to Add a Logical Const Wrapper to the Standard Library Technical Report

Program construction in C++ for Scientific Computing

Introduction to Move Semantics in C++ C and C

C++ Objects Overloading Other C++ Peter Kristensen

7 TEMPLATES AND STL. 7.1 Function Templates

Design Principles for a Beginning Programming Language

Financial computing with C++

async and ~future (Revision 3)

Using Enum Structs as Bitfields

p0407r2 - Allocator-aware basic_stringbuf

common_type and duration

p0408r4 - Efficient Access to basic_stringbuf s Buffer Including wording from p0407 Allocator-aware basic_stringbuf

Assignment #1 Advanced Programming in C /2018. NPRG051 Advanced programming in C++ - Assignment #1

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

Classes and Operators. Ali Malik

and the Unified Universe

Modules: ADL & Internal Linkage

Object-Oriented Programming

Other C++11/14 features

Layout-compatibility and Pointer-interconvertibility Traits

Programming 2. Object Oriented Programming. Daniel POP

Document Number: P0429R4 Date: Reply to: 0.1 Revisions... 1

Proposing Standard Library Support for the C++ Detection Idiom, v2

Transcription:

Implicit Evaluation of auto Variables and Arguments Document number: N4035 (update of N3748) Authors: Joël Falcou University Paris XI, LRI Peter Gottschling SimuNova Herb Sutter Microsoft Date: 2013-08-30 Project: Programming Language C ++, Evolution Working Group Reply to: Peter.Gottschling@simunova.com Revision to N3748 1. Prioritized syntax changed. 2. Third alternative introduced. 3. Library-based disabling introduced. 4. Some type traits removed. Altogether, the proposal is a clear simplification to its predecessor. 1 Motivation Type detection for variables from expressions return type: auto x= expr; has proven high usability. However, it fails to meet most users expectations and preferences when proxies or expression templates (ET) are involved, e.g.: matrix A, B; // setup A and B auto C= A B; Many people would expect C to be of type matrix as well. Whether C is a matrix depends on the implementation of operator. In the case that the operator returns a matrix then C is a matrix. For the sake of performance, computationally expensive operators very often return an Expression Template and delay the evaluation to a later point in time when it can be performed more efficiently because we know the entire expression and where the result is stored so that we can avoid the creation and destruction of a temporary. The impact of this approach to the beforementioned example is that C is not of type matrix but of some intermediate type that was probably only intended to be used internally in a library. 1

2 Moreover, we assume that even people who are aware of expression templates will very often prefer the evaluated object (here a matrix containing the product of A and B) and not an unevaluated or partially evaluated object (representing the product of A and B). We therefor need a mechanism to evaluate objects of certain types implicitly and sufficient control over this mechanism. 2 Goals The implicit evaluation shall: 1. Enable class implementers to indicate that objects of this class are evaluated in an auto statement; 2. Enable them to determine the type of the evaluated object; 3. Enable them to implement the evaluation; 4. Allow programmers to explicitly disable this evaluation; 5. Provide information about the return type; 6. Allow for efficient use as function arguments; 7. Establish a compact and intuitive notation; and 8. Maximize backward compatibility. 3 Example For the sake of illustration, we start with a typical implementation of expression templates: class product expr; // forward declaration class matrix... matrix& operator=(const product expr& product) / perform matrix product here / } class product expr... inline product expr operator (const matrix& A, const matrix& B) return product expr(a, B); } int main() matrix A, B; // setup A and B auto C= A B; // type of C is thus product expr } The auto variable C yield the type of the assigned expression which is in this case product expr not matrix. We could have written:

3 matrix C= A B; and C would obviously be a matrix and also contain the evaluated product. In the example above, the anonymous object product expr(a, B) apparently represents the product of A and B and the product of two matrices is a matrix as well. Thus, to meet the users typical expectations/preferences, we need to express how we create from an object representing A B an object that actually is A B. 4 Solution To achieve the goal that the type of C becomes matrix we know of three approaches: Operator notation; using declaration; and Specialization of decay. In discussions in the Chicago meeting and the reflector, the using declaration found the strongest consensus. We therefore, focus on this one and mention the alternatives later 4.1 Preferred Approach It was suggested in the reflector to introduce an operator auto to enable this implicit evaluation. In the example above, we would expand the implementation of product expr: class product expr public: product expr(const matrix& arg1, const matrix& arg2) : arg1(arg1), arg2(arg2) } using auto= matrix; private: const matrix &arg1, &arg2; The actual evaluation can be implemented in both classes: Either in matrix with a constructor accepting product expr; or In product expr with a conversion operator towards matrix. 4.2 Alternative Approaches Operator notation: class product expr... matrix operator auto()... } The idea was to introduce a new operator like:

4 The advantage of this form is that the implicit evaluation could be implemented independently from constructors and conversion operators. However, such generality seems to be rarely necessary according to current experience and feedback. Furthermore, the syntax of the conversion operator with return type deduction is so close that a lot of confusion would be expected. decay: Arno Schödl suggests using specialization of decay. The type trait decay reflects the type behavior of auto variables, i.e. typename decay<decltype(expr)>::type yield the type of variable x in auto x= expr;. He suggests to turn the semantics around and define auto x= expr; as: typename std::decay<decltype(expr)>::type x=expr; In this case, the type of the implicit evaluation can be customized by specializing std::decay. 4.3 Disabling the Implicit Evaluation In several situations, the programmer will need the unevaluated object and still likes to use the automatic type deduction. For this purpose, we propose denoting the declaration with the keyword explicit: explicit auto D= A B; Daveed Vandevorde remarked that the evaluation could also be disabled on the library level: auto D= noeval(a B); where noeval wraps the expression (for later unwrapping): struct noeval type const T& ref; noeval type(const T& ref) : ref(ref) } operator T const&() return ref; } using auto= T const&; auto noeval(const T& ref) return noeval type(ref); } We have no strong preference to any of the two approaches. 4.4 Reflection To refer to the return type of the operator auto, we propose the following template alias: using auto result type=...; When no operator auto is define the template alias returns T. For the types from this proposal it would be therefor:

5 Type expression auto result type<product expr> auto result type<matrix> Result matrix matrix 5 Backward Compatibility The implicit evaluation only applies on types that are equipped with an using auto declaration and existing code is not affected. 6 Consistency No matter what semantics we choose, we do want to end up where these cases are consistent: // case 1: local variable auto x = expr; // case 2: function parameter template<class T> void f( T x ); f( expr ); // case 3: lambda parameter auto f = []( auto x ) f( expr ); Today these are identical (except only that case 1 can deduce initializer list, and there is some pressure to remove that inconsistency). We believe these should stay identical. We propose that all type-deduced variables and parameters with value semantic are subject to implicit evaluation in the same way. All forms of references are not implicitly evaluated. 7 Summary We proposed a user-friendly method to deal with expression templates and proxies for local variables by introducing an implicit evaluation. 8 Wording To be done!