简体   繁体   中英

C++ value definition in cpp file and extra qualification

I am programming a template matrix with multi-threading. I need my matrix to be able to work with this code line (which i cannot change, it's a demand from my program):

Matrix<Complex>::setParallel(false);

so for this parallel (which is a bool decides if to use multi-threading or not) must be static.

So at start i defined it like that:

template<class T>
class Matrix
{
private:
...
public:
static bool parallel;
...
};

but then i got this error:

... undefined reference to 'Matrix<int>::parallel'

after a quick search i got to this question in stack overflow: Undefined reference to a static member

so i go ahead and to what the answers said. so i changed my code to:

   template<class T>
    class Matrix
    {
    private:
    ...
    public:
    static bool Matrix::paraller;
    ...
    };

and now i get this error:

extra qualification 'Matrix<T>::' on member 'paraller' [-fpermissive]

(note: i also tried static "bool Matrix::paraller;" instead, didn't help.

now i don't know how to get rid of the extra qualification error without getting back the undefined reference again.

if that matters, the whole code is in a file named: "Matrix.hpp", which i cannot change (another demand from my project).

what should i do?

Proper static class members usage is best described in this code snippet

struct A
{
   static bool concurrent;
};

A::concurrent = false;

or, if the member is const

struct B
{
   static const bool concurrent = false;
};

Specifying the template static class member is exactly the same. And one thing come out: static member initialization must be available at the scope of declaration . This means, you can't decouple declaration out of implementation - they must be exactly in the same program unit. Nevertheless, this is the common requirement for every template unit, whether it is an object, a function, etc.

Thus, creating a non-const template static class member is performed this way

template <typename T, typename U, typename... Rest>
struct TemplateStruct
{
   static U variable;
}

template <typename T, typename U, typename... Rest>
TemplateStruct<T, U, Rest...>::variable = U();

Where U may be any type you want, while it has a default constructor .

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