sz ppeter
sz ppeter

Reputation: 1902

template class partial specialization with different non-type template parameter

Is it possible to "partial specialize" a template class with different non-type template parameter values? More specifically, I am trying to combine the use of std::vector and std::array into one class according to different non-type template argument, something like this:

template<typename T, int Size>  //if Size given, use std::array stuff
class MyArray:public std::array<T, Size> {...}

template<typename T> //if Size is not given, use std::vector stuff
class MyArray:public std::vector<T> {...}

But the second template will be a redefined template error. I tried using std::enable_if, but have no idea how to use properly it here.

Upvotes: 0

Views: 173

Answers (1)

John Zwinck
John Zwinck

Reputation: 249093

You can use a sentinel value:

template<typename T, int Size = -1>  //if Size given, use std::array stuff
class MyArray:public std::array<T, Size> {};

template<typename T> //if Size is not given, use std::vector stuff
class MyArray<T, -1>:public std::vector<T> {};

Demo: https://godbolt.org/z/XpJ254

Upvotes: 2

Related Questions