Change constexpr class members in different subclasses

I have a base class, with 2 static const members - the second one being a constexpr of the first one:

constexpr int square(int n)
{
return n * n;
}

class BaseClass
{
public:
static const int original = 5;
static const int squared = square(original);
};

Which works perfectly. but I also want to create a subclass that changes only "original", and gets the changed "squared" "for free".

class SubClass : public BaseClass
{
public:
static const int original = 3;
// squared should be 9, not 25
};

Is there any way of doing this, or something similar?
Yes. Make it a template parameter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <iostream>

constexpr int square(int n) {return n*n;}

template<int N = 5>
class BaseClass
{
public:
    static const int original = N;
    static const int squared = square(N);
};

class SubClass : public BaseClass<3>
{
};



int main()
{
    std::cout << BaseClass<>::original << std::endl;
    std::cout << BaseClass<>::squared << std::endl;
    std::cout << SubClass::original << std::endl;
    std::cout << SubClass::squared << std::endl;
    
    return 0;
}


This way you get both original and squared "for free"
Topic archived. No new replies allowed.