Template variable

Currently, I have the following template without templates:

class Vector{ 
  public:
    double data[3];
 };
static Vector *myVariable;
void func() {
  myVariable->data[0] = 0.;
}
int main() {
  myVariable = new Vector();
  func();
}

Then I want to change the dimension:

template<int DIM> class Vector{ 
  public:
    double data[DIM];
 };
static Vector<3>* myVariable;
void func() {
  myVariable->data[0] = 0.;
}
int main() {
  myVariable = new Vector<3>();
  func();
}

But I finally also want to change my variable, with the size:

template<int DIM> class Vector{ 
  public:
    double data[DIM];
 };
template<int DIM> static Vector<DIM> *myVariable;

void func() {
  myVariable->data[0] = 0.;
  // or perform any other operation on myVariable
}
int main() {
  int dim = 3; 

  if (dim==3)
    myVariable = new Vector<3>();
  else
    myVariable = new Vector<4>();

  func();
}

However, this latest version of the code causes an error: this static variable cannot be templated ("C2998: Vector * myVariable cannot be a template definition").

How can I fix this error without a complete reorganization (for example, to inherit the Vector template class from a non-templated class, which will require more expensive calls to virtual methods or manually create several myVariables of different sizes)? Maybe I'm just tired and don’t see the obvious answer: s

: , , , . , , , .

!

+5
5

, !

template<int DIM> class Vector{ 
  public:
    double data[DIM];
 };
static void *myVariable;

template<int DIM>
void func() {
((Vector<DIM>*)myVariable)->data[0] = 0.;
  // or perform any other operation on myVariable
}
int main() {
  int dim = 3; 

  if (dim==3)
  {
    myVariable = (void*) new Vector<3>();
    func<3>();
  }
  else
  {
    myVariable = (void*) new Vector<4>();
    func<4>();
   }


}
0

- , . , , , . , , .

Vector<3> Vector<4> . template<int DIM> static Vector<DIM> *myVariable ; .

+2
template<int DIM> static Vector<DIM> *myVariable;

. .

, , , std::vector<T>. - , , , .

+1

std::array - , .

0

Vector<3>and Vector<4>are completely different types and have no formal relationship to each other. The fact that they look similar from your point of view does not matter.

If you want them to be equivalent to a specific type, we have a name for this: interfaces

template <typename Scalar = float>
class BasicVector {
public:
    typedef Scalar * iterator;
    virtual ~ BasicVector () {}

    virtual size_t   size  () const = 0;
    virtual iterator begin ()       = 0;
    virtual iterator end   ()       = 0;
};

template <unsigned N, typename Scalar = float>
class Vector : public BasicVector <Scalar> {
    Scalar m_elements [N];
public:
    using Scalar :: iterator;
    size_t   size  () const {return N;}
    iterator begin ()       {return m_elements;}
    iterator end   ()       {return m_elements + N;}
};

int main () {
    BasicVector * a;
    a = new Vector <3>;
    a = new Vector <4>;
}
0
source

All Articles