开发者

Default args in template

开发者 https://www.devze.com 2022-12-30 06:07 出处:网络
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 开发者_如何学Goshould be the type an

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 开发者_如何学Goshould be the type and its value should be 64.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消