Thread: Data init inside of template class function

  1. #1
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607

    Data init inside of template class function

    Let's say I have a matrix template class that will work on matrices of any data type (not any size though since concatenation is diff for diff sizes). In the ctor I need to set the matrix to the identity matrix or:

    1 0 0 0
    0 1 0 0
    0 0 1 0
    0 0 0 1

    Code:
    template<class Data_Type> class Matrix
    {
      Data_Type mdata[4][4];
      public:
        Matrix(void);
    };
    
    template<class Data_Type> Matrix<Data_Type>::Matrix(void)
    {
      mdata[0][0]=<Data_Type>1;
      mdata[0][1]=<Data_Type>0;
      mdata[0][2]=<Data_Type>0;
      mdata[0][3]=<Data_Type>0;
    
      mdata[1][0]=<Data_Type>0;
      mdata[1][1]=<Data_Type>1;
      mdata[1][2]=<Data_Type>0;
      mdata[1][3]=<Data_Type>0;
    
      mdata[2][0]=<Data_Type>0;
      mdata[2][1]=<Data_Type>0;
      mdata[2][2]=<Data_Type>1;
      mdata[2][3]=<Data_Type>0;
    
      mdata[3][0]=<Data_Type>0;
      mdata[3][1]=<Data_Type>0;
      mdata[3][2]=<Data_Type>0;
      mdata[3][3]=<Data_Type>1;
    }
    Will <Data_Type> typecast the 1 and 0 to the correct data type? Or should I place the Data_Type within a typecast like:

    matrix[0][0]=(Data_Type)1;


    If this is the wrong way to do this, how would I go about initializing the array with values of the correct data type?

    Or is this cast unecessary since mdata is already of type Data_Type. Will the compiler automatically cast the values to the correct type?

    I know that instead of using an array I could use a class from the standard class library, but I chose not to.

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    I believe the correct casting syntax would be -

    mdata[0][0]=static_cast<Data_Type>(1);
    //etc

    which would then fail at compile time if no conversion was possible (such as creating a matrix of std::strings). If you needed this to work on non-primitives without a suitable conversion operator then you could specialise.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  2. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM
  3. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM