syntax highlight

Tuesday, 7 June 2011

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):

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }
void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "n"; }
int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "n"; return 123; }

template <class... Args>
auto wrap(Args... a) -> decltype( do_something(a...) ) { 
	std::cout << __PRETTY_FUNCTION__ << "n";
	return do_something(a...);
}

int main() {
	wrap();
	wrap("nice");
	int x = wrap(42);
	std::cout << x << "n";
	return 0;
}

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:

void foo() {}

Is the same as:

auto foo() -> void {}

1 comment:

  1. [...] 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 [...]

    ReplyDelete