Welcome back! Last time, we looked at how to use the auto keyword in Visual C++ 2010 to implicitly declare local variables based on their initialization (see The Concurrency Runtime and Visual C++ 2010: Automatic Type Deduction). This week we’ll look at yet another great Visual C++ 2010 language feature that you can use when you write code that uses the Concurrency Runtime: decltype.
Imagine that you are writing reusable dataflow components that use the Asynchronous Agents Library. One of these components might be a message-block type that takes two addends and returns their sum. You can create a function, let’s call it make_dataflow_adder, that creates a Concurrency::transformer object. This transformer object takes as input the addends (as a std::tuple object) and produces their sum as output:
In this example, UNKNOWNtype remains as a placeholder. What should this type be, T1, T2, or something else? operator+ for objects of type T1 and T2 does not always produce a result of type T1 or T2. For instance, the following example shows a case where operator+ for objects of type A and B produces a result of type int:
One way to resolve UNKNOWNtype might be to add a third template argument to the make_dataflow_adder function, say TResult, and force the user to provide the result type. Aside from being somewhat of an inconvenience, what if your user is extending your library and does not know what type to provide?
Visual C++ 2010 provides the decltype keyword as a great way to solve this. Simply put, the decltype keyword provides the type of the provided expression. When you use the decltype keyword to rewrite the make_dataflow_adder function, you eliminate the need for a third template type parameter and create code that is more usable:
The following shows a complete example that uses the revised make_dataflow_adder function:
This example produces the following output:
4 + 42 = 46
"Hello, " + "World!" = "Hello, World!"
(3.0,4.0) + (2.0,-1.0) = (5,3)
A(50) + B(25) = 75
Although the decltype keyword was created primarily for library developers, anyone who is interested in writing generic, reusable code can make use of this feature.
For more information about decltype, including how to use decltype and auto to declare a function that has a late-specified return type, see decltype Type Specifier and Stephan’s post Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1.
Next time we’ll look at rvalue references, a Visual C++ language feature that can help you improve the performance of your applications that use Concurrency Runtime.