tags:

views:

68

answers:

2

Is it possible to have something like this:

template<class T = unsigned = 64>
class X
{
};

Which basically says that if nothing is specified then unsigned should be the type and its value should be 64.

+3  A: 

Not really. You could do something close though:


template < typename T = unsigned, T value = 64>
struct X{};

Edit: Dawned on me reading your other answer that there's something else you could do if you really wanted to:


template < unsigned N = 64 >
struct unsigned_
{
  typedef unsigned type;
  enum { value = N };
};

// alternative versions...int, long, etc...

template < typename T = unsigned_<64> >
struct X {};

This creates a bunch more work for the user though. You could address some of that by using boost::enable_if and is_fundamental so that the user could supply a fundamental type without you breaking down because you're looking for T::type and T::value.

So, while there is no way to do exactly what you're looking for...depending on how ugly you want to get you could get pretty darn close from the user's perspective.

Noah Roberts
+5  A: 

Taken literally, it doesn't make sense. Explain what are you trying to do first.

Templates in C++ have three kind of parameters: 1) type parameters, 2) value (non-type) parameters, 3) template parameters.

When you declare a parameter as class T it is a type parameter (first kind). It's "value" is actually a type. unsigned, for example. I.e. the "value" of T is unsigned. unsigned will be substituted instead of T in this instantiation of class X template. Parameter T can't have any numerical value, like 64.

Yet, you seem to be trying to create some kind of hybrid between kind 1 and kind 2 parameters. Firstly it is impossible. Secondly, there's no way to figure out what semantic meaning it could possibly have. Please, clarify your intent.

If you want to pass a numerical value, you have to create a template parameter of the second kind: a value parameter, as in

template <unsigned N = 64>
class X {
};

So, you need to decide first, what kind of template parameter you really need: a type parameter or a value parameter. Or maybe both. You haven't provided any details about your class X, so there's no way to guess what you are trying to do.

AndreyT