# Templated identity matrix with parameterize order?

Discussion in 'C++' started by Steven T. Hatton, Oct 11, 2004.

1. ### Steven T. HattonGuest

The following works:

template <typename T>
struct ID3M{
static const T ID[3][3];
};

template <typename T>
const T ID3M<T>::ID[3][3] = {{1,0,0},{0,1,0},{0,0,1}};

Is there a way to generalize this to take a parameter specifying the
order(number of elements per row)? The first part's easy:

template <typename T, unsigned ORDER>
struct IDM{
static const T ID[ORDER][ORDER];
};

But how can that be initialized to have 1's along the main diagonal and 0's
elsewhere?
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Steven T. Hatton, Oct 11, 2004

2. ### Patrick KowalzickGuest

Dear Steven,

I am a little bit scared not to answer your question, and then I will get a
harsh response.

template <typename T, size_t dim>
struct IDM
{

static size_t size1() { return dim; }
static size_t size2() { return dim; }

T operator[](const size_t & index1, const size_t & index2) const
{
// range checking if needed
if (index1 == index2) return 1;
else return 0;
}
};

Regards,
Patrick

Patrick Kowalzick, Oct 11, 2004

3. ### Steven T. HattonGuest

Patrick Kowalzick wrote:

> Dear Steven,
>
> I am a little bit scared not to answer your question, and then I will get
> a harsh response.
>
> template <typename T, size_t dim>
> struct IDM
> {
>
> static size_t size1() { return dim; }
> static size_t size2() { return dim; }
>
> T operator[](const size_t & index1, const size_t & index2) const
> {
> // range checking if needed
> if (index1 == index2) return 1;
> else return 0;
> }
> };

Yes. I thought about it. I even wrote the code, and then realized it won't
serve my purposes. I can't pass it as an array, and I'm not sure it will
have the same performance as using an actual array. I did come up with /a/
solution. It's not my idea of elegant, but it seems to work.

Java has something called static member initialization blocks which allow
you to execute code the first time a class is loaded. I don't know if that
could be added to C++, but it sure is nice. Then again, I don't believ you
can make the members of a Java array constant. If you can access the array,
you can modify it.

This is not a finished product, just a rough draft:

/***************************************************************************
* Copyright (C) 2004 by Steven T. Hatton *
* *
* *
* This program is free software; you can redistribute it and/or modify *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef TENSOR_HH
#define TENSOR_HH
#include "sth/util/Printable_IF.hh" // ABC: print() and operator<<(&ostream)
#include "vmath_impl.hh" // namespace_name
namespace sth{
namespace vmath{
namespace {
using sth::util:rintable_IF;
using std::string;
using std:stream;
}

template <typename T, unsigned ORDER>
class IDM{
T _m[ORDER][ORDER];
public:
typedef const T (&ref)[ORDER][ORDER];
IDM()
:ID(_m)
{
for(unsigned i = 0; i < ORDER; i++)
{
for(unsigned j = 0; j < ORDER; j++)
{
_m[j] = i == j ? T(1): T(0);
}
}
}
ref ID;
};

template<typename T, unsigned RANK, unsigned ORDER>
class Tensor: public Printable_IF {
public:
typedef const T (&ref)[ORDER][ORDER];
static const string class_name;
static const unsigned _RANK = RANK;
static const unsigned _ORDER = ORDER;

Tensor()
{}

virtual ostream& print(ostream& out) const;

protected:
static const ref _ID;
static const IDM<T, ORDER> _IDM;
};

template<typename T, unsigned RANK, unsigned ORDER>
const string Tensor<T, RANK, ORDER>::class_name = "Tensor<T,RANK,
ORDER>";

template<typename T, unsigned RANK, unsigned ORDER>
const IDM<T, ORDER> Tensor<T, RANK, ORDER>::_IDM = IDM<T, ORDER>();

template<typename T, unsigned RANK, unsigned ORDER>
const T (&Tensor<T, RANK, ORDER>::_ID)[ORDER][ORDER] = Tensor<T, RANK,
ORDER>::_IDM.ID;

template<typename T, unsigned RANK, unsigned ORDER>
ostream& Tensor<T, RANK, ORDER>:rint(ostream& out) const
{
return out << namespace_name << "::" << class_name << "\n";
}

}
}
#endif

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Steven T. Hatton, Oct 11, 2004
4. ### Rob WilliscroftGuest

Steven T. Hatton wrote in news: in
comp.lang.c++:

> The following works:
>
> template <typename T>
> struct ID3M{
> static const T ID[3][3];
> };
>
> template <typename T>
> const T ID3M<T>::ID[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
>
> Is there a way to generalize this to take a parameter specifying the
> order(number of elements per row)? The first part's easy:
>
> template <typename T, unsigned ORDER>
> struct IDM{
> static const T ID[ORDER][ORDER];
> };
>
>
> But how can that be initialized to have 1's along the main diagonal
> and 0's elsewhere?

#include <iostream>

template < unsigned Order >
struct array2
{
int array[ Order ][ Order ];

typedef int const (&const_array1_t)[ Order ];

const_array1_t operator [] ( unsigned i ) const
{
return array[ i ];
}

array2()
{
for ( unsigned i = 0; i < Order; ++i )
{
for ( unsigned j = 0; j < Order; ++j )
{
array[ i ][ j ] = int( i == j );
}
}
}
};

template < unsigned Order >
struct eg
{
static array2< Order > const id;
};

template < unsigned Order>
array2< Order > const eg< Order >::id;

int main()
{
for ( unsigned i = 0; i < 4; ++i )
{
for ( unsigned j = 0; j < 4 ; ++j )
{
if ( j ) std::cout << ", ";

std::cout << eg< 4 >::id[ i ][ j ];
}
std::cout << '\n';
}
}

Note the complete lack of UPPERCASE identifier's, excepting
single character template paramiters, such things should be
reserved for preprocesor #define's, anything else is asking
for trouble.

HTH.

Rob.
--
http://www.victim-prime.dsl.pipex.com/

Rob Williscroft, Oct 11, 2004
5. ### Patrick KowalzickGuest

Dear Steven,

> Java has something called static member initialization blocks which allow
> you to execute code the first time a class is loaded. I don't know if

that
> could be added to C++, but it sure is nice.

Something like this? I hope it is compliant, but I think so.

#include <iostream>

struct StaticInit
{
StaticInit()
{
if ( !getinit() ) init();
}
void init()
{
std::cout << "Just called the first time...." << std::endl;
}
bool getinit() {
static bool initzed = false;
if (initzed) return true;
initzed = true;
return false;
}
};

int main()
{
{
StaticInit A;
}
StaticInit B;
return 0;
}

Patrick Kowalzick, Oct 11, 2004
6. ### Patrick KowalzickGuest

Better like this (a lit clearer and with possibility to init directly):

#include <iostream>

struct StaticInit
{
StaticInit()
{
static_init();
}

static void static_init()
{
static bool initzed = false;
if (!initzed)
{
initzed = true;
initcalled();
}
}

static void initcalled()
{
std::cout << "Just called the first time...." << std::endl;
}
};

int main()
{
StaticInit::static_init();
{
StaticInit A;
}
StaticInit B;
return 0;
}

Regards,
Patrick

Patrick Kowalzick, Oct 11, 2004
7. ### Steven T. HattonGuest

Patrick Kowalzick wrote:

> Better like this (a lit clearer and with possibility to init directly):
>
> #include <iostream>
>
> struct StaticInit
> {
> StaticInit()
> {
> static_init();
> }
>
> static void static_init()
> {
> static bool initzed = false;
> if (!initzed)
> {
> initzed = true;
> initcalled();
> }
> }
>
> static void initcalled()
> {
> std::cout << "Just called the first time...." << std::endl;
> }
> };
>
>
>
> int main()
> {
> StaticInit::static_init();
> {
> StaticInit A;
> }
> StaticInit B;
> return 0;
> }

In TC++PL(SE) (http://www.research.att.com/~bs/3rd.html) this kind of
approach is discussed. IIRC, there were some qualifications involving

What I was talking about in Java is shown in this example from TJPL(3E) page
49:

class Primes {
static int[] knownPrimes = new int[4];
// static int knownPrimes[4];

static { // *static* *initialization* *block*
knownPrimes[0] = 2;
for(int i = 1; i < knownPrimes.length; i++)
//for(size_t i = 0; i < sizeof(knownPrimes)/sizeof(knownPrimes[0]);i++)
knownPrimes = nextPrime();
}
// declaration of nextPrime ...
}

But, as I said, you can't make the elements of knownPrimes constant. If you
can access the array, you can change the elements.

Perhaps I could cast away constness to initialize my arrays? Is that
safe...wise?

I believe what I'm doing with the initialization at the point of definition
in the kludge I posted earlier is effectively similar to what you are
showing above. I find the syntax rather awkward, but it works.

I'm confident the CPP would provide a means of creating the nested {{{..
{0,0,...,1,0,0,...,0}...}} of arbitrary depth. I am trying very hard to
_never_ use function or object type macros. That's part of the reason I'm
working on my own vector math library. Every time I looked at the
currently available libraries, I found macros were being used. I'm trying
to determine where they are actually necessary, and what the C++ native
alternatives to the existing macros might be.
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Russell

Steven T. Hatton, Oct 12, 2004
8. ### Steven T. HattonGuest

Rob Williscroft wrote:

> #include <iostream>
>
> template < unsigned Order >
> struct array2
> {
> int array[ Order ][ Order ];
>
> typedef int const (&const_array1_t)[ Order ];
>
> const_array1_t operator [] ( unsigned i ) const
> {
> return array[ i ];
> }
>
> array2()
> {
> for ( unsigned i = 0; i < Order; ++i )
> {
> for ( unsigned j = 0; j < Order; ++j )
> {
> array[ i ][ j ] = int( i == j );
> }
> }
> }
> };
>
> template < unsigned Order >
> struct eg
> {
> static array2< Order > const id;
> };
>
>
> template < unsigned Order>
> array2< Order > const eg< Order >::id;
>
> int main()
> {
> for ( unsigned i = 0; i < 4; ++i )
> {
> for ( unsigned j = 0; j < 4 ; ++j )
> {
> if ( j ) std::cout << ", ";
>
> std::cout << eg< 4 >::id[ i ][ j ];
> }
> std::cout << '\n';
> }
> }

This certainly seems close, and it has some very good ideas in it. The one
thing I believe it lacks is the ability to convert array2 to int[Order
[Order]. I'm not sure if a conversion operator can be invoked when passing
a reference to array2. I'll have to experiment.

> preprocesor #define's,

With the one exception of header guards, I don't do that.
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Steven T. Hatton, Oct 12, 2004
9. ### Gerhard WespGuest

Steven T. Hatton <> wrote:
> serve my purposes. I can't pass it as an array, and I'm not sure it will
> have the same performance as using an actual array. I did come up with /a/

You konw about expression templates (ETs)? This is the way modern LA
packages are typically implemented in C++. A matrix is not a concrete
type, but a class of types (a so-called ``concept''). This may be one
or more templates with some common properties like:

- member functions giving the number of rows and columns
- an element type
- an access operator
- ...

ET's have numerous advantages over simplistic approaches with a single
matrix type.

Cheers
-Gerhard

Gerhard Wesp, Oct 13, 2004
10. ### Patrick KowalzickGuest

Dear Steven,

> I'm confident the CPP would provide a means of creating the nested {{{..
> {0,0,...,1,0,0,...,0}...}} of arbitrary depth. I am trying very hard to
> _never_ use function or object type macros. That's part of the reason I'm
> working on my own vector math library. Every time I looked at the
> currently available libraries, I found macros were being used. I'm trying
> to determine where they are actually necessary, and what the C++ native
> alternatives to the existing macros might be.

I like macros , but I try to avoid them as well. And I do not mind if
there are macros in the libs, espacially when I use them as a "black box".

There are quite some reasons to use macros in libraries, e.g.:
-having different versions for debugging / not debugging
-having different versions for testing / stable
-implement workarounds for non compliant compilers (nearly every one)
-repetetive code, e.g. for classes which are similar and only have semantic
differences

The rest I forgot, but I think macros are handy tools, and I do not want to
miss them.

Regards,
Patrick

Patrick Kowalzick, Oct 13, 2004