proton proton - 2 months ago 6
C++ Question

C++ template class change static member's value

I have the following classes -
class

Matrix<T>
that stands for a matrix of objects of type
T
, and it's super class
baseMAtrix
that holds a static boolean variable
parallel_
common to all types of
Matrix<T>
.

I want to access
parallel_
but it seems my code does not link -

class baseMatrix {
protected:
static bool parallel_;
};

template<class T>
class Matrix : baseMatrix{

public:
static void setParallel (bool parallel){
if(parallel != baseMAtrix::parallel_){
cout << "message" << endl;
}
baseMAtrix::parallel_ = parallel;
}
};


I get the this message -

`CMakeFiles/ex3.dir/Tester.cpp.o:Tester.cpp:(.rdata$.refptr._ZN10baseMatrix9_parallelE[.refptr._ZN10baseMatrix9_parallelE]+0x0): undefined reference to `baseMatrix::_parallel'
collect2: error: ld returned 1 exit status`


the
Tester.cpp
file is where I call
setParallel
-

Matrix<int>::setParallel(true);


is this the proper way to call
setParallel
?

is this the proper way to access
baseMatrix::_parallel
?

Answer

If you want to stay just-header-friendly, you could change base class to template:

template<class T>
class baseMatrix 
{
protected:
    static bool _parallel;
};

template<class T>
bool baseMatrix<T>::_parallel;

template<class T>
class Matrix : baseMatrix<void>
...

This way there is no need for baseMatrix::_parallel in cpp file.

Comments