dshin
dshin

Reputation: 2398

Specifying a subset of optional template parameters

Say I have a template class like

template<class FooPolicy=DefaultFooPolicy, 
  class BarPolicy=DefaultBarPolicy, 
  class BazPolicy=DefaultBazPolicy> HighlyCustomizableClass;

Now I declare some typedefs:

typedef HighlyCustomizableClass<AlternativeFooPolicy> VersionA;
typedef HighlyCustomizableClass<DefaultFooPolicy,AlternativeBarPolicy> VersionB;
typedef HighlyCustomizableClass<DefaultFooPolicy,DefaultBarPolicy,AlternativeBazPolicy> VersionC;

This can get unwieldy, especially if we have even more template parameters. Furthermore, if another Policy type is added to HighlyCustomizableClass, then existing typedef statements become invalid. This doesn't seem necessary.

It'd be much nicer to be able to write these as:

typedef HighlyCustomizableClass<FooPolicy=AlternativeFooPolicy> VersionA;
typedef HighlyCustomizableClass<BarPolicy=AlternativeBarPolicy> VersionB;
typedef HighlyCustomizableClass<BazPolicy=AlternativeBazPolicy> VersionC;

Is it possible in theory for c++ to allow this syntax? If so, are there any plans for future standards to adopt it? If not, is there some reason why this sort of syntax would be problematic?

Upvotes: 3

Views: 117

Answers (2)

Jan Herrmann
Jan Herrmann

Reputation: 2767

The supported syntax in C++ is

typedef HighlyCustomizableClass<FooPolicy<AlternativeFooPolicy>> VersionA;

The idiom is called named template parameter and can be implemented with help of Boost Parameter Library. If you don't like boost you can look at C++ Templates The Complete Guide 16.1 Named template arguments. Source code is available.

Upvotes: 1

iavr
iavr

Reputation: 7637

It's not exaclty what you'd like, but with template aliases in C++11 you can say

template<
   class foo=def_foo, 
   class bar=def_bar, 
   class baz=def_baz
> custom;

template<class foo=alt_foo>
using VersionA = custom<foo>;

template<class bar=alt_bar>
using VersionB = custom<def_foo, bar>;

template<class baz=alt_baz>
using VersionC = custom<def_foo, def_bar, baz>;

I've taken the liberty to make names shorter :-)

Template parameters are identified by their position in the parameter list (just like function parameters) and not by their name (like attributes of HTML elements, for instance)!.

Upvotes: 2

Related Questions