Search code examples
c++templatesclass-template

Template specialization with dependent values


Using templates for array size seems straightforward:

template <size_t N>
struct MyArray
{
    char array[N];
};

What I'd like to do, though, is set the array size based on something else:

enum MyEnum {Hi, Lo};

template <MyEnum T, size_t N>
struct MyArray
{
    MyEnum type() { return T; }
    char array[N];
};

How do I set N to 10 when MyEnum is Hi, and 200 when MyEnum is Lo?

What I'd like to do is say

MyArray<Lo> lo; // Result in MyArray<Lo, 200>
MyArray<Hi> hi; // Result in MyArray<Hi, 10>

rather than having to say

MyArray<Lo, 200> lo;
MyArray<Hi, 10> hi;

Is this possible?


Solution

  • You can make a default value for N right away, same as you'd do with normal function parameters:

    enum MyEnum { Hi, Lo };
    
    template <MyEnum T, size_t N = (T == Hi ? 10 : 200)> // parentheses for clarity
    struct MyArray { ... };
    

    Live example