There are several classes that are identical, except for one static variable which must be unique for each class.
What is the C++ syntax to set that up?
The following example is my failed attempt using template class.
Code_LayerLock is a template class.
The Code_LayerLock classes are identical, except for the static refLayerState variable.
Here is the tricky part: I want each unique Code_LayerLock class that the compiler generates to have it's own static refLayerState variable.
But when the example is compiled, the compiler finds this error on line 32:
|
template_ref.cpp:32:54: error: redefinition of ‘State& Code_LayerLock<State>::refLayerState’
|
The error happens because class Code_LayerLock is still the same name, even though the compiler generated a unique class for the template parameter declaration.
Maybe template class is not the best approach in this situation.
How would you assign a unique static variable to each class, to otherwise identical classes?
I will be using GCC: 4.8.1, std=c++98 for Arduino.
Thank you.
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 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
class LayerStateMF
{
public:
void lock(int layer) { std::cout << "LayerStateMF::layer=" << layer << std::endl; }
};
class Code_StateFunc
{
public:
void lock(int layer) { std::cout << "Code_StateFunc::layer=" << layer << std::endl; }
};
template <class State>
class Code_LayerLock
{
private:
const int layer;
static State& refLayerState; //refLayerState is static and different for each class
public:
Code_LayerLock(const int layer) : layer(layer) {}
void press() { refLayerState.lock(layer); }
};
LayerStateMF MF;
Code_LayerLock<LayerStateMF> l_MF(0);
template<class State> State& Code_LayerLock<State>::refLayerState = MF; //static variable definition
Code_StateFunc l_NASHold;
Code_LayerLock<Code_StateFunc> l_TenKey(1);
template<class State> State& Code_LayerLock<State>::refLayerState = l_NASHold; //error: redefinition
int main()
{
l_MF.press();
//l_TenKey.press();
}
|
Expected output:
1 2
|
LayerStateMF::layer=0
Code_StateFunc::layer=1
|