Skip to content

The “result_of” template

October 20, 2011

C++11 has several new features which add the ability for the compiler to automatically deduce the type of an expression. These include decltype, declval, auto and of course result_of.

The result_of template should be used when you only have the types of objects. It takes a single function-type template argument, and contains a type member which gives the result when an object of the specified template type is called with arguments of the specified types.

For example, if you write:

std::result_of<T(U,V)>::type

then you will get the type when an object of type T is called with arguments of type U and V.

This can be particularly useful when writing a template function which returns something that depends on template parameters. You can do something like this:

template 
std::result_of<T(U)>::type
foo(T t, U u)
{
  //do something that ends up returning t(u)
}

The declaration of result_of is as follows:

template <class> class result_of;
template <class F, class... ArgTypes> 
class result_of<F(ArgTypes...)>;
Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: