Nicolás Brailovsky


A modern blog

C++0X Sneak Preview

date Date: Apr 13th, 2011

Congratulations, you have stumbled upon my C++0x research draft. I’m writing a series of articles regarding the new standard of the language, and what you can find here are mostly drafts and early versions, made public with the purpose of having these available for early reviewers. Keep in mind anything you may find here may still be in review and not 100% accurate, then again that comment can apply to all information you may find in the web.

Cool C++0X features I

C++0X brings some very cool changes, and I wanted to start a series of posts regarding some of these changes, with a small explanation of each new feature (that I currently understand, at least), an example of its usage and why I think it’s a cool thing. Notice these two may be mutually exclusive, some of these may just be cool but I wouldn’t recommend using them on a day to day basis. An example of a very cool feature which I wouldn’t normally use in a project is the one I want to write about today: variadic templates.

"C++ gives you enough rope to shoot yourself"

What’s not to love about variadic templates? Its name implies (correctly) that it uses templates, and it also has a “variadic” thingy, which you can use to look smart since no one really knows what it means.

Templates themselves can quickly get complicated if used by unexperienced padawans in the art of martial C++, yet their hypnotic beauty draws every programmer to use them just like flies are drawn to fire. When used correctly they can produce very elegant code; if not for the template programmer, at least for the end user. Yet in all their power, templates in C++ have been lacking a fundamental aspect: a variable number of arguments.

There are ways to work around this limitation, like using a list of types paired with a template-paramlist-object. Sounds familiar? (I know it doesn’t, don’t worry). You could also generate N constructors, one overload for each parameter count. The drawback, exponential compile time (say, TR1). These are all hacks, which are in place only because there wasn’t a safe way of passing a list of types associated with a list of arguments. This is over now with variadic templates in C++0X.

So, what kind of problem would variadic templates solve? Let’s name a few:

* A typesafe varargs function (a function with a variable number of arguments)

* Easily create a template object which acts as a tuple

* An easier implementation of a  reduce (inject) function

This entry is getting quite long so we’ll start seeing these examples on the next post.

Cool C++0X features II, Variadic templates: What’s wrong with varargs

Last time we explained what variadic templates are. We’ll see what they can do now. We mentioned that solving the problem of having a type-safe varargs is one of the best ways of applying variadic templates, but what’s varargs?

Varargs functions (from C world, not even from C++!) are functions which have a variable number of arguments, just like printf. These are usually very dangerous functions, since they are not typesafe. Let’s see how they are implemented with an example:

  1. #include <stdarg.h>
  2.  
  3. #include <iostream>
  4.  
  5. // My god, it’s full of bugs
  6.  
  7. void va_println(int args_left, …) {
  8.  
  9.    va_list arg_lst;
  10.  
  11.    va_start(arg_lst, args_left);
  12.  
  13.    while(args_left–) {
  14.  
  15.       const char *p = va_arg(arg_lst, const char*);
  16.  
  17.       std::cout << p;
  18.  
  19.    }
  20.  
  21.    va_end(arg_lst);
  22.  
  23. }
  24.  
  25. int main() {
  26.  
  27.    va_println(3, "Hola ", "mundo", "\n");
  28.  
  29.    return 0;
  30.  
  31. }

This implementation of a function with variable arguments is, more or less, the best C can give us, yet it riddled with bugs and hidden problems. Let’s go one by one:

Arg num will get out of sync

You need to specify the list of args as well as how many you have. That WILL get out of sync. Trust me, it’s just a mater of time. And when it does, you’ll have a coredump.

Type-unsafe

You just tell varargs “Hey, get me an int”. And it will give you an int, no warranties included. If it was supposed to be a short instead, though luck, you end up with a coredump.

No, really, coredump

Where are so many coredumps coming from, you may ask. Easy, varargs it’s just a way of handling the stack. Calling va_arg just moves the stack pointer by the sizeof the datatype you requested. That means no compile-time checks are included.

No pod types

Remember POD types? Try running this code:

  1. #include <stdarg.h>
  2.  
  3. struct X { X(){} };
  4.  
  5. void va_println(int args_left, …) {
  6.  
  7.    va_list arg_lst;
  8.  
  9.    va_start(arg_lst, args_left);
  10.  
  11.    while(args_left–) {
  12.  
  13.       X *p = va_arg(arg_lst, X*);
  14.  
  15.    }
  16.  
  17.    va_end(arg_lst);
  18.  
  19. }
  20.  
  21. int main() {
  22.  
  23.    X x, y, z;
  24.  
  25.    va_println(3, x, y, z);
  26.  
  27.    return 0;
  28.  
  29. }

And how do we fix it?

The fix is easy. Too easy. You just need C++0X. We will discuss why this is better next time, but just as a sneak peak:

  1. void println() {}
  2.  
  3. template <typename H, typename… T> void println(H p, T… t) {
  4.  
  5.    std::cout << p;
  6.  
  7.    println(t…);
  8.  
  9. }
  10.  
  11. int main() {
  12.  
  13.    println("Hola", " mundo ", 42, \n);
  14.  
  15.    return 0;
  16.  
  17. }

Remember to compile using -std=c++0x in gcc.

Cool C++0X features III: Variadic templates, a fix for varargs

Last time we saw why a function with varargs may bring lots of problems. Then we saw how to solve it, but never explained why that last solution doesn’t have the problems the varargs solution had, nor how does it work. Let’s start by copying the solution here:

  1. // Stop condition
  2.  
  3. void println() {}
  4.  
  5. // General case
  6.  
  7. template <typename H, typename… T>
  8.  
  9. void println(H p, T… t)
  10.  
  11. {
  12.  
  13.    std::cout << p;
  14.  
  15.    println(t…);
  16.  
  17. }
  18.  
  19. int main() {
  20.  
  21.    println("Hola", " mundo ", 42, \n);
  22.  
  23.    return 0;
  24.  
  25. }

It certainly looks much better than the varargs function, even though some new strange syntax has been introduced. Keep in mind some template-foo is required, not only because of the syntax but because we’ll be talking about functional programming too.

With all that intro (the last 2 articles were just an intro!) now we are in a good shape to ask what a variadic template really is. In its easiest form, it’s just a list of template arguments, like this:

  1. template <typename… T> void foo(T… t) {}

That simple template can accept as many parameters as you need, of any type. This is much safer than a vararg because:

  • Doesn’t require the user to specify the number of args passed to foo, so it just can’t get out of sync
  • It’s typesafe; since C++ templates are type-safe, variadic templates are type safe too. You won’t be able to request an int where a char is required, you’ll just get a compiler error.
  • Compile time check: you get type safety just because this is all compiled code. If it doesn’t compile, you get an error (albeit a little cryptic).
  • POD types support
  • Better performance; small gain, but a gain indeed. Since this is all done in compile time there’s no need to handle the stack dynamically, nor of having a loop getting the args. It’s all known when you compile, thus the compiler can just optimize the hell out of everything

Pretty neat, huh? But how does it work? Variadic templates are actually very similar to how Haskell handles lists, you get all the arguments as a list of types in which you can either get the head or the tail. To do something useful, get the head and continue processing the tail recursively.

  1. template <typename H, typename… T>
  2.  
  3. void do_something(H h, T… t)
  4.  
  5. {
  6.  
  7.         // Do something useful with h
  8.  
  9.         really_do_something(h);
  10.  
  11.         // Continue processing the tail
  12.  
  13.         do_something(t…);
  14.  
  15. }

Of course, you’ll eventually need a condition to stop processing: (we’ll explain the new syntax later)

  1. void do_something()
  2.  
  3. {
  4.  
  5.         // Do nothing :)
  6.  
  7. }

When the list is completely processed the empty do_something function will be called. Easy, right? But it does have a lot of weird syntax. Let’s see what each of those ellipses mean:

  • When declaring typename… T you are saying “here goes a list of types”. That is, when you use ellipses after the typename (or class) declaration but before the name of the type, then you are expecting a list of types there.
  • When declaring T… t you are saying t is a list of objects with different type. That is, you declared T… as a type which holds a list of types, therefore t, of type T, is an instance of a list of objects, each of different type
  • When you write t…, you are saying “expand the list of arguments”. You declared t as a list of objects, but you have no way of accessing each of those objects, just to the list as a whole. When you write the name of the object followed by ellipses, you are saying expand these types and their instance for the called function

With all that in mind, let’s put together our typesafe printf:

  1. // Condition to stop processing
  2.  
  3. void println() {}
  4.  
  5. // Println receieves a list of arguments. We don’t know it’s type nor
  6.  
  7. // how many there are, so we just get the head and expand the rest
  8.  
  9. template <typename H, typename… T>
  10.  
  11. void println(H p, T… t)
  12.  
  13. {
  14.  
  15.         // Do something useful with the head
  16.  
  17.         std::cout << p;
  18.  
  19.         // Expand the rest (pass it recursively to println)
  20.  
  21.         println(t…);
  22.  
  23. }
  24.  
  25. int main() {
  26.  
  27.         // See how it works even better than varargs?
  28.  
  29.    println("Hola", " mundo ", 42, \n);
  30.  
  31.    return 0;
  32.  
  33. }

Next time, we’ll see a more complex (and fun) example of variadic templates.]]>

Cool C++0X features IV: Variadic templates again

Last time we finally solved the varargs problem. Let’s review what we learned:

  • Variadic templates let us create something receiving a variable set of arguments
  • We can process the head of that set, then recursively process the tail
  • It adds weird new syntax
    • When declaring typename… T you are saying “here goes a list of types”
    • When declaring T… t you are saying t is a list of objects with different type
    • When you write t…, you are saying “expand the list of arguments”
  • It’s type safe
  • It’s very neat to confuse your coworkers

So, what can we do with it besides implementing our own version of printf? Let’s do something better, let’s try adding up a list of numbers to start flexing our variadic templatefooness (?).

What’s the usual way of adding a list of numbers? In templates, that is. We need something like this:

  1. sum (H:T) <- H + sum(T)
  2.  
  3. sum () <- 0

Of course, in C++ templates you don’t have values, you just have types. We could implement it like this (if this looks like a new language you may want to check my template metaprogramming series):

  1. #include <iostream>
  2.  
  3. struct Nil{};
  4.  
  5. template <typename H, typename T=Nil> struct Lst {
  6.  
  7.         typedef H Head;
  8.  
  9.         typedef T Tail;
  10.  
  11. };
  12.  
  13. template <
  14.  
  15.                 template<typename A, typename B> class Op,
  16.  
  17.                 typename Head,
  18.  
  19.                 typename Lst>
  20.  
  21. struct intForeach
  22.  
  23. {
  24.  
  25.         typedef typename intForeach
  26.  
  27.                 < Op, typename Lst::Head, typename Lst::Tail >::result Next;
  28.  
  29.         typedef typename Op< Head, Next >::result result;
  30.  
  31. };
  32.  
  33. template <
  34.  
  35.                 template<typename A, typename B> class Op,
  36.  
  37.                 typename Head>
  38.  
  39. struct intForeach <Op, Head, Nil>
  40.  
  41. {
  42.  
  43.         typedef Head result;
  44.  
  45. };
  46.  
  47. template <
  48.  
  49.                 typename Lst,
  50.  
  51.                 template<typename A,
  52.  
  53.                 typename B>
  54.  
  55.                 class Op>
  56.  
  57. struct Reduce
  58.  
  59. {
  60.  
  61.         typedef typename intForeach
  62.  
  63.                 < Op, typename Lst::Head, typename Lst::Tail >::result result;
  64.  
  65. };
  66.  
  67. template <int N> struct Num {
  68.  
  69.         const static int value = N;
  70.  
  71. };
  72.  
  73. template <typename A, typename B> struct Sum {
  74.  
  75.         static const int r = A::value + B::value;
  76.  
  77.         typedef Num<r> result;
  78.  
  79. };
  80.  
  81. int main() {
  82.  
  83.         std::cout << Reduce<
  84.  
  85.                 Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8> > > > >,
  86.  
  87.                 Sum >::result::value << "\n";
  88.  
  89.         return 0;
  90.  
  91. }

Nothing too fancy, plain old recursion with a sum. Yet it’s quite verbose, can we make this a little bit more terse and, hopefully, more clear? Yes, we can. Take a look at that Lst, Lst<… It sucks. And it’s the perfect place to use variadic templates, we just need to construct a structure getting a list of ints, like this:

  1. template <
  2.  
  3.         // The operation we wish to apply
  4.  
  5.         template<typename A, typename B> class Op,
  6.  
  7.         // Current element to process
  8.  
  9.         class H,
  10.  
  11.         // All the rest
  12.  
  13.         class… T>
  14.  
  15. struct Reduce_V
  16.  
  17. {
  18.  
  19.         // TODO
  20.  
  21. }

That one should look familiar from last time article. Now, to implement a reduce operation we need to operate the current element with the result of reducing the tail, so we have to do something like this:

  1.         // Remember how T… means to expand T for the next instance
  2.  
  3.         typedef typename Reduce_V<Op, T…>::result Tail_Result

There’s something missing. Can you see what? The ending condition, of course. Let’s add it and we’ll get something like this:

  1. template <
  2.  
  3.         // The operation we wish to apply
  4.  
  5.         template<typename A, typename B> class Op,
  6.  
  7.         // Current element to process
  8.  
  9.         class H,
  10.  
  11.         // All the rest
  12.  
  13.         class… T>
  14.  
  15. struct Reduce_V
  16.  
  17. {
  18.  
  19. template <
  20.  
  21.         // The operation we wish to apply
  22.  
  23.         template<typename A, typename B> class Op,
  24.  
  25.         // Current element to process
  26.  
  27.         class H,
  28.  
  29.         // All the rest
  30.  
  31.         class… T>
  32.  
  33. struct Reduce_V
  34.  
  35. {
  36.  
  37.         // Remember how T… means to expand T for the next instance
  38.  
  39.    typedef typename Reduce_V<Op, T…>::result Tail_Result;
  40.  
  41.         // Reduce current value with the next in line
  42.  
  43.         typedef typename Op<H, Tail_Result>::result result;
  44.  
  45. }

And using it is very simple too:

  1. std::cout << Reduce_V< Sum, Num<1>, Num<2>, Num<3>, Num<4>>::result::value << "\n";

Next time we’ll see another example for variadic templates and a new C++0x feature.

Cool C++0X features V: Templates and angle brackets, a short interlude

In the heart of C++ template metaprogramming and code obfuscation, lies the (ab)use of angle brackets. This seemingly innocent token can turn the most clean looking code into the mess that template-detractors like so much to complain about.

C++0x doesn’t do much to clean up this mess, it’s probably impossible, but it does offer a subtle feature to improve the legibility of C++ template code, a nifty little feature we have (inadvertently) used.

Up to C++0x, having two angle brackets together (>>) was parsed as the shift operator (like the one cout uses), meaning that if you had nested templates a lot of compiler errors ensued. C++0x corrects this, meaning that code which in C++ would be like this:

  1.         Reduce<Sum, Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8> > > > > >

Can now be written like this:

  1.         Reduce<Sum, Lst<Num<2>, Lst<Num<4>, Lst<Num<6>, Lst< Num<8>>>>>>

Aaand, back to the normal programming…

Cool C++0X features VI: A variadic wrapper

Let’s work on the last variadic exercise, a wrapper. Say you have something like this:

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. int main() {
  6.  
  7.         do_something();
  8.  
  9.         return 0;
  10.  
  11. }

And you want to wrap do_something with something else (Remember __PRETTY_FUNCTION__?). This is a solution, the worst one though:

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void wrap() {
  6.  
  7.         std::cout << __PRETTY_FUNCTION__ << "\n";
  8.  
  9.         do_something();
  10.  
  11. }
  12.  
  13. int main() {
  14.  
  15.         wrap();
  16.  
  17.         return 0;
  18.  
  19. }

Why is it so bad? Let’s say you don’t control do_something, you just control the wrapper. You may not even control main(), it may be beyond your scope. That means each time do_something changes, or adds an overload, you have to change your code. That’s ugly and you should already know how to set up a variadic function to forward the arguments to do_something. Give it a try, next time the solution.

Cool C++0X features VII: A variadic wrapper solution

Last time we were trying to build a wrapper function, in which we don’t control the class being wrapped nor the user of the wrapper (meaning we can’t change either of those but they could change without warning).

This was the first approach:

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void wrap() {
  6.  
  7.         std::cout << __PRETTY_FUNCTION__ << "\n";
  8.  
  9.         do_something();
  10.  
  11. }
  12.  
  13. int main() {
  14.  
  15.         wrap();
  16.  
  17.         return 0;
  18.  
  19. }

Yet, as we saw, it’s not scalable, when either part changes the whole things break. We proposed then a variadic template solution, which, if you tried it yourself, should look something like this:

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7. template <class… Args>
  8.  
  9. void wrap(Args… a) {
  10.  
  11.         std::cout << __PRETTY_FUNCTION__ << "\n";
  12.  
  13.         do_something(a…);
  14.  
  15. }
  16.  
  17. int main() {
  18.  
  19.         wrap();
  20.  
  21.         wrap("nice");
  22.  
  23.         return 0;
  24.  
  25. }

That’s better. Now we don’t care about which parameters do_something should get, nor how many of them are there supposed to be, just how it’s called. If you read the previous entries on variadic templates this should be a walk in the park. It still has a flaw though: we need to know the return type of do_something!

Is there a way to write a wrapper without knowing the return type of a function you are wrapping? Yes, in Ruby you can, but you can do it in C++0x too, and we’ll see how to do it next time.

A closing remark: You could do something like this wrapping everything in a class:

  1. #include <iostream>
  2.  
  3. struct Foo {
  4.  
  5.         void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7.         void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  8.  
  9. };
  10.  
  11. template <class Base>
  12.  
  13. struct Wrapper {
  14.  
  15.         template <class… Args>
  16.  
  17.         void wrap(Args… a) {
  18.  
  19.                 std::cout << __PRETTY_FUNCTION__ << "\n";
  20.  
  21.                 T::do_something(a…);
  22.  
  23.         }
  24.  
  25. };
  26.  
  27. int main() {
  28.  
  29.         Wrapper<Foo> w;
  30.  
  31.         w.wrap();
  32.  
  33.         w.wrap("nice");
  34.  
  35.         return 0;
  36.  
  37. }

The above works just fine, but due to some limitations in the current (stable) version of gcc we will use the former version (the problem with this form will be clear later, I promise).

Cool C++0X features VIII: Variadic wrapper and type inference with decltype

The wrapper function we built last time looks something like this now:

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7. template <class… Args>
  8.  
  9. void wrap(Args… a) {
  10.  
  11.         std::cout << __PRETTY_FUNCTION__ << "\n";
  12.  
  13.         do_something(a…);
  14.  
  15. }
  16.  
  17. int main() {
  18.  
  19.         wrap();
  20.  
  21.         wrap("nice");
  22.  
  23.         return 0;
  24.  
  25. }

But, as we saw last time, this approach has the problem of requiring the return type of do_something to be known before hand. What can we do to remove this dependency? In C++, not much. You can’t really declare a type based on the return type of another function. You do have the option of using lots of metaprogramming wizardy, but this is both error prone and ugly (see Stroustroup’s C++0x FAQ).

C++0x lets you do some magic with type inference using decltype; decltype(expr) will yield the type of that expression. It works quite similarly as sizeof does; decltype is resolved at compile time and the expression with which it’s being called is not evaluated (more on this later).

How would this work on our example?

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7. int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "\n"; return 123; }
  8.  
  9. template <class… Args>
  10.  
  11. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  12.  
  13.         std::cout << __PRETTY_FUNCTION__ << "\n";
  14.  
  15.         return do_something(a…);
  16.  
  17. }
  18.  
  19. int main() {
  20.  
  21.         wrap();
  22.  
  23.         wrap("nice");
  24.  
  25.         int x = wrap(42);
  26.  
  27.         std::cout << x << "\n";
  28.  
  29.         return 0;
  30.  
  31. }

Try it (remember to add -std=c++0x) it works great! The syntax is not so terribly difficult to grasp as it was with variadic templates. The auto keywords says “hey, compiler, the return type for this method will be defined later”, and then the -> actually declares the return type. This means that the auto-gt idiom isn’t part of typedecl but a helper, which in turns means that even if not useful, this is valid C++0x code:

  1. auto wrap() -> void {
  2.  
  3. }

This means that we have three interesting components to analyze in this scenario:

  • -> (delayed declaration)
  • auto
  • decltype

We’ll go over each one the next time.

Closing remark:

At first I choose the following example to introduce delayed return types and decltype (warning, untested code ahead):

  1. #include <iostream>
  2.  
  3. struct Foo {
  4.  
  5.         void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7.         void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  8.  
  9.         int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "\n"; return 123; }
  10.  
  11. };
  12.  
  13. // Untested code ahead
  14.  
  15. // This makes g++ coredump (v 4.4.5)
  16.  
  17. template <class T>
  18.  
  19. struct Wrap : public T {
  20.  
  21.         template <class… Args>
  22.  
  23.         auto wrap(Args… a) -> decltype( T::do_something(a…) ) {
  24.  
  25.                 std::cout << __PRETTY_FUNCTION__ << "\n";
  26.  
  27.                 return T::do_something(a…);
  28.  
  29.         }
  30.  
  31. };
  32.  
  33. int main() {
  34.  
  35.         Wrap<Foo> w;
  36.  
  37.         w.wrap();
  38.  
  39.         w.wrap("nice");
  40.  
  41.         std::cout << w.wrap(42) << "\n";
  42.  
  43.         return 0;
  44.  
  45. }

Though this looks MUCH better (and useful), at the time of writing this article mixing variadic templates with decltypes in a template class makes g++ segfault. It should be valid C++, but I can’t assure it’s correct code since I’ve never tried it.

Cool C++0X features IX: delayed type declaration

In the last two entries we worked on a wrapper object which allows us to decorate a method before or after calling (hello aspects!), or at least that’s what it should do when g++ fully implements decltypes and variadic templates. Our wrapper function looks something like this (check out the previous entry for the wrapper object):

  1. #include <iostream>
  2.  
  3. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  4.  
  5. void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6.  
  7. int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "\n"; return 123; }
  8.  
  9. template <class… Args>
  10.  
  11. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  12.  
  13.         std::cout << __PRETTY_FUNCTION__ << "\n";
  14.  
  15.         return do_something(a…);
  16.  
  17. }
  18.  
  19. int main() {
  20.  
  21.         wrap();
  22.  
  23.         wrap("nice");
  24.  
  25.         int x = wrap(42);
  26.  
  27.         std::cout << x << "\n";
  28.  
  29.         return 0;
  30.  
  31. }

After the example, we were left with three new syntax changes to analyze:

  • -> (delayed declaration)
  • decltype
  • auto

Let’s study the -> operator this time:

-> (delayed declaration)

This is the easiest one. When a method is declared auto (I’ve left this one for the end because auto is used for other things too) it means its return type will be defined somewhere else. Note that in this regard the final implementation differs from Stroustroup’s FAQ.

The -> operator in a method’s definition says “Here’s the return type”. I’ll paste the same simple example we had last time, the following two snippets of code are equivalent:

  1. void foo() {
  2.  
  3. }
  1. auto foo() -> void {
  2.  
  3. }

Cool C++0X features X: type inference with decltype

After creating a wrapper object on the last entries, we were left with three syntax changes two analyze:

We already saw the first, and we’ll be talking about the other two this time. This was the original wrapper function which led us here:

  1. template <class… Args>
  2.  
  3. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  4.  
  5.         std::cout << __PRETTY_FUNCTION__ << "\n";
  6.  
  7.         return do_something(a…);
  8.  
  9. }

Back on topic:

decltype

This operator (yes, decltype is an operator) is a cousin of sizeof which will yield the type of an expression. Why do I say it’s a cousin of sizeof? Because it’s been in the compilers for a long time, only in disguise. This is because you can’t get the size of an expression without knowing it’s type, so even though it’s implementation has existed for a long time only now it’s available to the programmer.

One of it’s interesting features is that the expression with which you call decltype won’t be evaluated, so you can safely use a function call within a decltype, like this:

  1. auto foo(int x) -> decltype( bar(x) ) {
  2.  
  3.         return bar(x);
  4.  
  5. }

Doing this with, say, a macro, would get bar(x) evaluated twice, yet with decltype it will be evaluated only once. Any valid C++ expression can go within a decltype operator, so for example this is valid too:

  1. template <typename A, typename B>
  2.  
  3. auto multiply(A x, B y) -> decltype( x*y )
  4.  
  5. {
  6.  
  7.         return x*y;
  8.  
  9. }

What’s the type of A and B? What’s the type of A*B? We don’t care, the compiler will take care of that for us. Let’s look again at that example, more closely:

-> (delayed declaration) and decltype

Why bother creating a delayed type declaration at all and not just use the decltype in place of the auto? That’s because of a scope problem, see this:

  1. // Declare a template function receiving two types as param
  2.  
  3. template <typename A, typename B>
  4.  
  5. // If we are declaring a multiplication operation, what’s the return type of A*B?
  6.  
  7. // We can’t multiply classes, and we don’t know any instances of them
  8.  
  9. auto multiply(A x, B y)
  10.  
  11. // Luckily, the method signature now defined both parameters, meaning
  12.  
  13. // we don’t need to expressly know the type of A*B, we just evaluate
  14.  
  15. // x*y and use whatever type that yields
  16.  
  17.         -> decltype( x*y )
  18.  
  19. {
  20.  
  21.         return x*y;
  22.  
  23. }

decltype

As you see, decltype can be a very powerful tool if the return type of a function is not known for the programmer when writing the code, but you can use it to declare any type, anywhere, if you are too lazy to type. If you, for example, are very bad at math and don’t remember that the integers group is closed for multiplication, you could write this:

  1.         int x = 2;
  2.  
  3.         int y = 3;
  4.  
  5.         decltype(x*y) z = x*y;

Yes, you can use it as VB’s dim! (kidding, just kidding, please don’t hit me). Even though this works and it’s perfectly legal, auto is a better option for this. We’ll see that on the next entry.

Cool C++0X features XI: type inference with auto

In the last four entries we worked on a simple example, like the one I’m pasting below, of type inference with decltype, which led us to learn about delayed type declaration and decltypes with auto. This time I want to focus just on the auto keyword instead.

  1. template <class… Args>
  2.  
  3. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  4.  
  5.         std::cout << __PRETTY_FUNCTION__ << "\n";
  6.  
  7.         return do_something(a…);
  8.  
  9. }

We saw last time how decltype can be used in a contrived way to create a local variable without specifying its type, only how to deduce the type for this variable. Luckily, that verbose method of type declaration can be summed up in the following way:

  1.         int x = 2;
  2.  
  3.         int y = 3;
  4.  
  5.         decltype(x*y) z = x*y;
  1.         int x = 2;
  2.  
  3.         int y = 3;
  4.  
  5.         auto z = x*y;

That’s right, when you are declaring local variables it’s easier and cleaner to just use auto. This feature isn’t even “in the wild” yet, so you can’t really predict what will people do with it, but it seems to me that limiting its use to local variables with a very short lived scope is the best strategy. We are yet to see what monstrosities the abuse of this feature will produce, and I’m sure there will be many. Regardless of their potential to drive insane any maintainers, its best use probably comes in loops.

In any C++ application, you’ll find code like this:

  1. for (FooContainer<Bar>::const_iterator i = foobar.begin(); i != foobar.end(); ++i)

This ugly code can be eliminated with something much more elegant:

  1. for (auto i = foobar.begin(); i != foobar.end(); ++i)

Looks nicer indeed, but we can improve it much further with other tools. We’ll see how the next time. For the time being, let’s see for waht what auto is not to be used.

When using auto, keep in mind it was designed to simplify the declaration of a variable with a complex or difficult to reason type, not as a replacement for other language features like templates. This is a common mistake:

Wrong 

  1. void f(auto x) {
  2.  
  3.         cout << x;
  4.  
  5. }
Right 

  1. template <T>
  2.  
  3. void f(T x) {
  4.  
  5.         cout << x;
  6.  
  7. }

It makes no sense to use auto in the place of a template, since a template means that the type will be completed later whereas auto means it should be deduced from an initializer.

Cool C++0X features XII: auto and ranged for, cleaner loops FTW

Last time we saw how the ugly

  1. for (FooContainer::const_iterator i = foobar.begin(); i != foobar.end(); ++i)

could be transformed into the much cleaner

  1. for (auto i = foobar.begin(); i != foobar.end(); ++i)

Yet we are not done, we can clean that a lot more using for range statements.

Ranged for is basically syntactic sugar (no flamewar intended) for shorter for statements. It’s nothing new and it’s been part of many languages for many years already, so there will be no lores about the greatness of C++ innovations (flamewar intended), but it still is a nice improvement to have, considering how tedious can be to write nested loops. This certainly looks much cleaner:

  1. for (auto x : foobar)

This last for-statement, even though it looks good enough to print and hang in a wall, raises a lot of questions. What’s the type of x? What if I want to change its value? Let’s try to answer that.

The type of the iterator will be the same as the type of the vector, so in this case x would be an int:

  1. std::vector foobar;
  2.  
  3. for (auto x : foobar) {
  4.  
  5.         std::cout << (x+2);
  6.  
  7. }

And now, what happens if you want to alter the contents of a list and not only display them? That’s easy too, just declare x as an auto reference:

  1. std::vector foobar;
  2.  
  3. for (auto&amp; x : foobar) {
  4.  
  5.         std::cout << (x+2);
  6.  
  7. }

This looks really nice but it won’t really do anything, for two different reasons:

* Ranged fors won’t work until g++ 4.5.6 is released

* The list is empty!

There are many ways to initialize that list, but we’ll see how C++0X let’s you do it in a new way the next time.

     Add A Comment

trackback Trackback URI | rsscomment Comments RSS