Quantcast
Viewing latest article 6
Browse Latest Browse All 11

Dev Corner – Decltype Keyword



The keyword decltype is new in Visual Studio 2010 and is available as well in GCC C++.  It is pretty simple you can get a type out of an expression.  I see it used most in cases where you don’t want to supply a typedef but would like to use the type of an existing variable; hopefully this example will help illustrate:

struct A
{
   int m_n;
};

int main()
{
   A a = {4};
   decltype(a.m_n) n = 6;   //n in the same as A::m_n which in an int
   a.m_n = n;
   return 0;
}

So with the example if the member variable m_n changes type from an int to anything else the variable n in the main function will be of the same type.  Using a typedef we could have supplied both m_n and n to be a type from the typedef.  Though if we made n an auto (on line 9) then n would be dependent on what got assigned to it (in this case 6 is an int so it would be an int type) instead of what it is assigning to (on line 10).

A large use of this keyword by professionals has to do with return types!  Take a look at the following:

template auto Add(const T& t, const U& u) -> decltype(t+u) { return t+u;}

This templated function can take any type T and U as input and will return the result of a type that makes sense which might not be either type T or type U.  Since the return-type specification comes before the function name and the function arguments; we do not know the names of the variables passed in (the lowercase t & u) in the return-type specification.  So we used the auto keyword and specify the return-type as a late-specified return type which may use the variable names (lowercase t & u).  This is not to say it couldn’t have been written without a late-specified return type which is shown in the example below:

template decltype((*(T*)0)+(*(U*)0)) Add(const T& t, const U& u) { return t+u;}

It appears to be a matter of preference whether you think using the decltype as a late-specified return type with auto is cleaner than specifying the return type without the auto keyword.  What do you think?  Do you see a use for the decltype keyword?  Are you understanding late-specified return type?

Image may be NSFW.
Clik here to view.
859-aj devcorner.jpg

Andrew “A.J.” Orians is a developer on the Windows version of Camtasia Studio. Though he enjoys programming he also likes puzzles, running, games, and a whole slew of other activities. He has been at TechSmith for something like five years and looks forward to being here for many more!

The post Dev Corner – Decltype Keyword appeared first on TechSmith Blogs.


Viewing latest article 6
Browse Latest Browse All 11

Trending Articles