In the
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
,
decltype
is a
keyword used to query the
type of an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
. Introduced in
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
, its primary intended use is in
generic programming
Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
, where it is often difficult, or even impossible, to express types that depend on
template
Template may refer to:
Tools
* Die (manufacturing), used to cut or shape material
* Mold, in a molding process
* Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs
Co ...
parameters.
As
generic programming
Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
techniques became increasingly popular throughout the 1990s, the need for a type-deduction mechanism was recognized. Many compiler vendors implemented their own versions of the operator, typically called
typeof
typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly s ...
, and some portable implementations with limited functionality, based on existing language features were developed. In 2002,
Bjarne Stroustrup
Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
proposed that a standardized version of the operator be added to the C++ language, and suggested the name "decltype", to reflect that the operator would yield the "declared type" of an expression.
decltype
's semantics were designed to cater to both generic library writers and novice programmers. In general, the deduced type matches the type of the object or function exactly as declared in the source code. Like the
sizeof
operator,
decltype
's operand is not evaluated.
Motivation
With the introduction of
template
Template may refer to:
Tools
* Die (manufacturing), used to cut or shape material
* Mold, in a molding process
* Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs
Co ...
s into the C++ programming language, and the advent of
generic programming
Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
techniques pioneered by the
Standard Template Library
The Standard Template Library (STL) is a Library (computer science), software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components ...
, the need for a mechanism for obtaining the type of an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
, commonly referred to as
typeof
typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly s ...
, was recognized. In generic programming, it is often difficult or impossible to express types that depend on template parameters,
in particular the return type of function template instantiations.
Many vendors provide the
typeof
operator as a compiler extension.
As early as 1997, before C++ was fully standardized, Brian Parker proposed a portable solution based on the
sizeof
sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of ''char''-sized units. Consequently, the construct ''sizeof (char)'' is guaranteed to be ' ...
operator.
His work was expanded on by Bill Gibbons, who concluded that the technique had several limitations and was generally less powerful than an actual
typeof
mechanism.
In an October 2000 article of ''
Dr. Dobb's Journal
''Dr. Dobb's Journal'' (''DDJ'') was a monthly magazine published in the United States by UBM Technology Group, part of UBM plc, UBM. It covered topics aimed at computer programmers. When launched in 1976, DDJ was the first regular periodical focu ...
'',
Andrei Alexandrescu
Andrei Alexandrescu (born 1969) is a Romanian-American C++ and D language programmer and author. He is particularly known for his pioneering work on policy-based design implemented via template metaprogramming. These ideas are articulated in ...
remarked that "having a typeof would make much template code easier to write and understand."
He also noted that "typeof and sizeof share the same backend, because sizeof has to compute the type anyway."
Andrew Koenig
Joshua Andrew Koenig (; August 17, 1968 – February 16, 2010) was an American character actor, film director, editor, writer, and human rights activist. He was known for his role as Richard "Boner" Stabone in ''Growing Pains''.
Early ...
and Barbara E. Moo also recognized the usefulness of a built-in
typeof
facility, with the caveat that "using it often invites subtle programming errors, and there are some problems that it cannot solve."
They characterized the use of type conventions, like the
typedef
typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (''alias'') for another data type, but does not create a new type, except in the obscure case of a qualified typedef of ...
s provided by the
Standard Template Library
The Standard Template Library (STL) is a Library (computer science), software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components ...
, as a more powerful and general technique.
However, Steve Dewhurst argued that such conventions are "costly to design and promulgate", and that it would be "much easier to ... simply extract the type of the expression."
In a 2011 article on
C++0x
C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
, Koenig and Moo predicted that "decltype will be widely used to make everyday programs easier to write."
In 2002,
Bjarne Stroustrup
Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
suggested extending the C++ language with mechanisms for querying the type of an expression, and initializing objects without specifying the type.
Stroustrup observed that the reference-dropping semantics offered by the
typeof
operator provided by the
GCC and
EDG compilers could be problematic.
Conversely, an operator returning a reference type based on the
lvalue-ness of the expression was deemed too confusing. The initial proposal to the C++ standards committee outlined a combination of the two variants; the operator would return a reference type only if the declared type of the expression included a reference. To emphasize that the deduced type would reflect the "declared type" of the expression, the operator was proposed to be named
decltype
.
One of the cited main motivations for the
decltype
proposal was the ability to write perfect
forwarding function templates.
It is sometimes desirable to write a generic forwarding function that returns the same type as the wrapped function, regardless of the type it is instantiated with. Without
decltype
, it is not generally possible to accomplish this.
An example, which also utilizes the ''
trailing-return-type'':
int& foo(int& i);
float foo(float& f);
template auto transparent_forwarder(T& t) −> decltype(foo(t))
decltype
is essential here because it preserves the information about whether the wrapped function returns a reference type.
Semantics
Similarly to the
sizeof
sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of ''char''-sized units. Consequently, the construct ''sizeof (char)'' is guaranteed to be ' ...
operator, the operand of
decltype
is unevaluated.
Informally, the type returned by
decltype(e)
is deduced as follows:
#If the expression
e
refers to a variable in local or namespace scope, a static member variable or a function parameter, then the result is that variable's or parameter's ''declared type''
#Otherwise, if
e
is an
lvalue,
decltype(e)
is
T&
, where
T
is the type of e; if e is an
xvalue, the result is
T&&
; otherwise, e is a
prvalue and the result is
T
.
#As a special case,
decltype(auto)
allows for type deduction like
auto
Auto may refer to:
* An automaton
* An automobile
* An autonomous car
* An automatic transmission
* An auto rickshaw
* Short for automatic
* Auto (art), a form of Portuguese dramatic play
* ''Auto'' (film), 2007 Tamil comedy film
* Auto (play), ...
but it preserves the value category of the initializer. More specifically, it is equivalent to
decltype(''initializer'')
.
These semantics were designed to fulfill the needs of generic library writers, while at the same time being intuitive for novice programmers, because the return type of
decltype
always matches the type of the object or function exactly as declared in the source code.
More formally, Rule 1 applies to unparenthesized ''id-expression''s and class member access expressions.
Example:
Note for added lines for bar(). Below the type deduced for "bar()" is plain int, not const int, because prvalues of non-class types always have cv-unqualified types, despite the statically declared different type.
const int&& foo();
const int bar();
int i;
struct A ;
const A* a = new A();
decltype(foo()) x1; // type is const int&&
decltype(bar()) x2; // type is int
decltype(i) x3; // type is int
decltype(a->x) x4; // type is double
decltype((a->x)) x5; // type is const double&
The reason for the difference between the latter two invocations of
decltype
is that the parenthesized expression
(a->x)
is neither an ''id-expression'' nor a member access expression, and therefore does not denote a named object.
Because the expression is an lvalue, its deduced type is "reference to the type of the expression", or
const double&
.
The fact that extra parentheses introduce a reference qualifier to the type can be a source of errors for programmers who do not fully understand
decltype
.
In December 2008, a concern was raised to the committee by Jaakko Järvi over the inability to use
decltype
to form a ''qualified-id'',
which is inconsistent with the intent that
decltype(e)
should be treated "as if it were a ''typedef-name''".
While commenting on the formal Committee Draft for
C++0x
C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
, the Japanese
ISO
ISO is the most common abbreviation for the International Organization for Standardization.
ISO or Iso may also refer to: Business and finance
* Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007
* Iso ...
member body noted that "a scope operator(::) cannot be applied to decltype, but it should be. It would be useful in the case to obtain member type(nested-type) from an instance as follows":
vector v;
decltype(v)::value_type i = 0; // int i = 0;
This, and similar issues pertaining to the wording inhibiting the use of
decltype
in the declaration of a
derived class
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
and in a
destructor call, were addressed by David Vandevoorde, and voted into the working paper in March 2010.
Availability
decltype
is included in the C++ Language Standard since
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
.
It is provided by a number of compilers as an extension.
Microsoft
Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washing ...
's
Visual C++ 2010 and later compilers provide a
decltype
type specifier that closely mimics the semantics as described in the standards committee proposal. It can be used with both
managed and native code.
The documentation states that it is "useful primarily to developers who write template libraries."
decltype
was added to the mainline of the
GCC C++ compiler in version 4.3,
released on March 5, 2008.
decltype
is also present in
Codegear
CodeGear is a wholly owned division of Embarcadero Technologies. CodeGear develops software development tools such as the Delphi Integrated development environment, the programming language Delphi, and the database server InterBase. Originally ...
's
C++ Builder 2009,
the
Intel C++ Compiler
Intel oneAPI DPC++/C++ Compiler and Intel C++ Compiler Classic are Intel’s C, C++, SYCL, and Data Parallel C++ (DPC++) compilers for Intel processor-based systems, available for Windows, Linux, and macOS operating systems.
Overview
Intel o ...
,
and
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC), ...
.
References
External links
Bjarne Stroustrup's C++0x FAQ entry for decltype
{{good article
C++
Articles with example C++ code