Saturday, 23 November 2013

Disclaim template template parameters

Use template template parameters C + + is difficult. I want to demonstrate the power and boost :: mpl show trick to describe patterns, completely abandoning the template template parameters. 
Demonstrate problem. There is a class that takes an object type and the type of container for this object.
template < typename T, typename Container>
 struct A
{
  typedef Container <T> type;
};

So you can not write, you should use the template template parameters, to indicate that the Container itself is structured.

Correctly write:
template < typename T, template < typename > class Container>
 struct A
{
  typedef Container <T> type;
};

Use this:
typedef A < int , STD :: vector > :: type type;

At the first use we get a compilation error. We have forgotten that std :: vector takes two parameters, one of which is usually the default. Well, we can rewrite:
template < typename T, template < typename , typename > class Container>
 struct A
{
  typedef Container <T, STD :: allocator <T>> type;
};

There are two obvious problems:
  1. We must look into the implementation of std :: vector, find out what type allocator used by default, and then use it.
  2. We wrote a template will not work if the container is more than one template parameter default.

I would like to avoid explicit default type and complex syntax template template parameters. Comes to the aid technique based on the use of placeholders boost :: mpl, are used to create a lambda metafunctions. Externally, the only difference is that you need to pass to our template is not the template container and container instantiated template placeholders, ie instead


typedef A < int , STD :: vector > :: type type;
write
typedef A < int , STD :: vector <boost::mpl::_1> > :: type type;

To instantiate instantiated placeholder container necessary type using boost :: mpl :: apply:
# Include <boost/mpl/apply.hpp> 
template < typename T, typename Container>
 struct A
{
  typedef  typename :: boost :: MPL apply <Container, T> :: type type;
};

Using this trick in real programming help simplify some of your intricate patterns.

No comments:

Post a Comment