Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a default template argument without having to use <> in C++?

Tags:

c++

templates

I have a struct being used somewhere which is declared as:

struct Foo
{
someArray[64];
//...other stuff
};

It is used extensively in many places, and I would like to change it to this:

template <size_t N = 64>
struct Foo
{
someArray[N];
//...other stuff
};

because there is one place (well four to be exact) where this struct needs to be used with a 128 byte array for correctness, but the penalty it introduces for ALL the other uses is not worth paying. In providing a default template argument I was hoping it would go through transparently, except for those in the know-how who need a wider internal array which would then declare Foo<128>. Unfortunately, it seems to force every use of it to say Foo<>. Is there a way around this?

like image 880
Palace Chan Avatar asked Dec 05 '25 14:12

Palace Chan


1 Answers

You cannot omit the angular brackets when instantiating a class template.

However, you can give a different name to your Foo class template (say, FooN) and then provide a type alias such as:

typedef FooN<> Foo;

This way, clients who were using the original, non-template version of Foo won't have to be changed, and clients that need the flexibility of overriding the default N can use the generic class template:

FooN<128> obj;
like image 134
Andy Prowl Avatar answered Dec 08 '25 04:12

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!