简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM