decltype

decltype

In the C++ programming language, decltype is an operator for querying the type of an expression. It was introduced in the current version of the C++ standard, C++11. Its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.

As generic programming 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, and some portable implementations with limited functionality, based on existing language features were developed. In 2002, Bjarne Stroustrup 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.

Contents

Motivation

With the introduction of templates into the C++ programming language, and the advent of generic programming techniques pioneered by the Standard Template Library, the need for a mechanism for obtaining the type of an expression, commonly referred to as typeof, was recognized. In generic programming, it is often difficult or impossible to express types that depend on template parameters,[1][2] in particular the return type of function template instantiations.[1]

Many vendors provide the typeof operator as a compiler extension.[3] As early as 1997, before C++ was fully standardized, Brian Parker proposed a portable solution based on the sizeof operator.[3] 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.[3] In an October 2000 article of Dr. Dobb's Journal, Andrei Alexandrescu remarked that "[h]aving a typeof would make much template code easier to write and understand."[4] He also noted that "typeof and sizeof share the same backend, because sizeof has to compute the type anyway."[4] Andrew Koenig 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."[5] They characterized the use of type conventions, like the typedefs provided by the Standard Template Library, as a more powerful and general technique.[5] 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."[6]

In 2002, Bjarne Stroustrup suggested extending the C++ language with mechanisms for querying the type of an expression, and initializing objects without specifying the type.[1] Stroustrup observed that the reference-dropping semantics offered by the typeof operator provided by the GCC and EDG compilers could be problematic.[1] 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.[1]

One of the cited main motivations for the decltype proposal, was the ability to write perfect forwarding function templates.[7] 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.[7] An example, which also utilizes the trailing-return-type:[7]

int& foo(int& i);
float foo(float& f);
 
template <class T> auto transparent_forwarder(T& t)> decltype(foo(t)) {
  return foo(t);
}

decltype is essential here because it preserves the information about whether the wrapped function returns a reference type.[8]

Semantics

Similarly to the sizeof operator, the operand of decltype is unevaluated.[9] Informally, the type returned by decltype(e) is deduced as follows:[1]

  1. 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
  2. If e is a function call or an overloaded operator invocation, decltype(e) denotes the declared return type of that function
  3. Otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e; if e is an rvalue, the result is T

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.[1] More formally, Rule 1 applies to unparenthesized id-expressions and class member access expressions.[10] For function calls, the deduced type is the return type of the statically chosen function, as determined by the rules for overload resolution.[11] Example:[10]

const int&& foo();
int i;
struct A { double x; };
const A* a = new A();
decltype(foo()) x1; // type is const int&&
decltype(i) x2; // type is int
decltype(a->x) x3; // type is double
decltype((a->x)) x4; // 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.[12] Because the expression is an lvalue, its deduced type is "reference to the type of the expression", or const double&.[9]

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,[13] which is inconsistent with the intent that decltype(e) should be treated "as if it were a typedef-name".[14] While commenting on the formal Committee Draft for C++0x, the Japanese 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":[15]

vector<int> 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 and in a destructor call, were addressed by David Vandevoorde, and voted into the working paper in March 2010.[16][17]

Availability

decltype is included in the current version of the C++ Language Standard, C++11.[10] It is provided by a number of compilers as an extension. Microsoft's Visual C++ 2010 compiler provides a decltype operator that closely mimics the semantics as described in the standards committee proposal. It can be used with both managed and native code.[8] The documentation states that it is "useful primarily to developers who write template libraries."[8] decltype was added to the mainline of the GCC C++ compiler in version 4.3,[18] released on March 5, 2008.[19] The operator is also present in Codegear's C++ Builder 2009,[20] the Intel C++ Compiler,[21] and Clang.[22]

References

  1. ^ a b c d e f g Gregor, Douglas; Järvi, Jaakko; Siek, Jeremy; Stroustrup, Bjarne (2003-04-28). "Decltype and auto". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1478.pdf. Retrieved 2009-08-13. 
  2. ^ Kalev, Danny (2008-05-08). "Clean Up Function Syntax Mess with decltype". DevX.com. http://www.devx.com/cplus/10MinuteSolution/37854/1954. Retrieved 2009-09-04. 
  3. ^ a b c Gibbons, Bill (2000-11-01). "A Portable "typeof" Operator". Dr. Dobb's Journal. http://www.ddj.com/cpp/184401310. Retrieved 2009-09-03. 
  4. ^ a b Alexandrescu, Andrei (2000-10-01). "Generic<Programming>: Mappings between Types and Values". Dr. Dobb's Journal. http://www.ddj.com/cpp/184403750. Retrieved 2009-09-03. 
  5. ^ a b Koenig, Andrew; Barbara E. Moo (2002-02-01). "C++ Made Easier: Naming Unknown Types". Dr. Dobb's Journal. http://www.ddj.com/cpp/184401487. Retrieved 2009-09-03. 
  6. ^ Dewhurst, Steve (2000-08-01). "Common Knowledge: A Bitwise typeof Operator, Part 1". Dr. Dobb's Journal. http://www.ddj.com/cpp/184401548. Retrieved 2009-09-03. 
  7. ^ a b c Dos Reis, Gabriel; Järvi, Jaakko; Stroustrup, Bjarne (2004-10-12). "Decltype and auto (revision 4)". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1705.pdf. Retrieved 2009-09-04. 
  8. ^ a b c "decltype Operator". Microsoft Corporation. http://msdn.microsoft.com/en-us/library/dd537655(VS.100,loband).aspx. Retrieved 2009-09-04. 
  9. ^ a b Dos Reis, Gabriel; Järvi, Jaakko; Stroustrup, Bjarne (2007-07-18). "Decltype (revision 7): proposed wording". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf. Retrieved 2009-09-04. 
  10. ^ a b c Becker, Pete. "Working Draft, Standard for Programming Language C++". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2914.pdf. Retrieved 2009-09-04. 
  11. ^ Miller, William M. (2009-08-03). "C++ Standard Core Language Defect Reports, Revision 65". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2937.html. Retrieved 2009-09-15. 
  12. ^ Miller, William M. (2009-08-03). "C++ Standard Core Language Closed Issues, Revision 65". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2938.html. Retrieved 2009-09-04. 
  13. ^ Miller, William M. (2009-09-29). "C++ Standard Core Language Active Issues, Revision 66". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html. Retrieved 2009-10-03. 
  14. ^ Dos Reis, Gabriel; Järvi, Jaakko; Stroustrup, Bjarne (2006-11-05). "Decltype (revision 6): proposed wording". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2115.pdf. Retrieved 2009-10-03. 
  15. ^ Miller, William M. (2009-08-03). "C++ CD1 Comment Status". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2939.html. Retrieved 2009-10-03. 
  16. ^ Miller, William M. (2010-03-29). "C++ Standard Core Language Defect Reports, Revision 69". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3084.html. Retrieved 2010-04-10. 
  17. ^ Vandevoorde, Daveed (2010-02-03). "Core issues 743 and 950: Additional decltype(...) uses". ISO/IEC JTC1/SC22/WG21 – The C++ Standards Committee. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3031.pdf. Retrieved 2010-04-10. 
  18. ^ "C++0x Support in GCC". Free Software Foundation. 2009-08-27. http://gcc.gnu.org/projects/cxx0x.html. Retrieved 2009-09-04. 
  19. ^ "GCC 4.3 Release Series". Free Software Foundation. 2009-08-13. http://gcc.gnu.org/gcc-4.3/. Retrieved 2009-09-04. 
  20. ^ "Type Specifier decltype (C++0x)". Embarcadero Technologies. http://docs.codegear.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/typespecifierdecltype_xml.html#. Retrieved 2009-09-04. 
  21. ^ "std, Qstd". Intel Corporation. http://software.intel.com/sites/products/documentation/hpc/compilerpro/en-us/cpp/win/compiler_c/copts/ccpp_options/option_std.htm. Retrieved 2009-09-04. 
  22. ^ Gregor, Douglas (2011-01-26). "New C++0x feature support in Clang". http://lists.cs.uiuc.edu/pipermail/cfe-dev/2011-January/013013.html. 

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужна курсовая?

Look at other dictionaries:

  • C++11 — C++11[1][2] или ISO/IEC 14882:2011[3] (в процессе работы над стандартом носил условное наименование C++0x[4][5])  новая версия стандарта языка C++, вместо ранее действовавшего ISO/IEC 14882:2003. Новый стандарт включает дополнения в ядре… …   Википедия

  • C++11 — C++11, also formerly known as C++0x,[1] is the name of the most recent iteration of the C++ programming language, replacing C++TR1, approved by the ISO as of 12 August 2011.[2] The name is derived from the tradition of naming language versions by …   Wikipedia

  • C++0x — C++0x  будущая версия стандарта языка C++, вместо ныне существующего ISO/IEC 14882:2003. Новый стандарт будет включать дополнения в ядре языка и расширение STL, включая большую часть TR1  кроме, вероятно, библиотеки специальных… …   Википедия

  • C++0x — is the planned new standard for the C++ programming language. It is intended to replace the existing C++ standard, ISO/IEC 14882, which was published in 1998 and updated in 2003. These predecessors are informally known as C++98 and C++03. The new …   Wikipedia

  • C++ — У этого термина существуют и другие значения, см. C. См. также: Си (язык программирования) C++ Семантика: мультипарадигмальный: объектно ориентированное, обобщённое, процедурное, метапрограммирование Тип исполнения: компилируемый Появился в …   Википедия

  • C++11 — C++11, anciennement connu sous le nom de C++0x[1], est la nouvelle norme pour le langage C++ en informatique. Elle a été approuvée unanimement le 12 août 2011[2]. Elle vise à remplacer la norme existante, ISO/CEI 14882, publiée en 1998 et mise à… …   Wikipédia en Français

  • Visual C++ — For Visual C#, see Microsoft Visual C Sharp. Visual C++ Developer(s) Microsoft Corporation Stable release Visual Studio 2010 / April 2010 …   Wikipedia

  • ConceptGCC — is a fork of the GNU C++ compiler that implements a preliminary version of the type concepts feature, originally planned for the forthcoming new ISO standard for the C++ programming language, known as C++0x. Concepts were removed from C++0x in… …   Wikipedia

  • Сравнение языков программирования — Эту статью следует викифицировать. Пожалуйста, оформите её согласно правилам оформления статей.  Условные обозначения  …   Википедия

  • Wikipedia:List of Wikipedians by number of edits — Shortcuts: WP:NOE WP:WBE WP:EDITS WP:MOSTEDITS This is a list of Wikipedians ordered by number of edits in the English language Wikipedia. Edits in all namespaces are counted; deleted edits have been included in recent versions. Click… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”