Created
April 17, 2012 19:17
-
-
Save sahib/2408386 to your computer and use it in GitHub Desktop.
Just playing with templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdexcept> // std::invalid_argument | |
#include <cstdio> // printf() | |
#include <cstdlib> // EXIT_SUCCESS | |
#include <cstring> // memset() | |
namespace NV | |
{ | |
template<typename FloatType, unsigned w, unsigned h> class matrix | |
{ | |
public: | |
/** | |
* @brief Initializes a matrix to empty values (0.0) | |
*/ | |
matrix() { | |
memset(_m,0,w*h*sizeof(FloatType)); | |
} | |
/** | |
* @brief Simply print the matrix to stdout | |
*/ | |
inline void print() const { | |
for(unsigned r = 0; r < h; r++) { | |
for(unsigned c = 0; c < w; c++) { | |
printf("%03.0f ",operator()(r,c)); | |
} | |
putchar('\n'); | |
} | |
} | |
/** | |
* @brief Get the element | |
* | |
* () was used instead of [] since [] can only hold one index | |
* | |
* @param r row | |
* @param c column | |
* | |
* @return a concrete float | |
*/ | |
inline FloatType& operator()(unsigned r,unsigned c) { | |
return _m[r][c]; | |
} | |
/** | |
* @brief Safer wrapper around operator() | |
* | |
* @param r See operator() | |
* @param c See operator() | |
* | |
* @return same as (), but FLAOT_MIN for invalid values | |
*/ | |
inline FloatType& at(unsigned r, unsigned c) throw(std::invalid_argument) { | |
if(r < w && c < h) | |
return operator()(r,c); | |
else | |
throw std::invalid_argument("bad index"); | |
} | |
/** | |
* @brief Const version of operator() | |
*/ | |
inline FloatType operator()(unsigned r, unsigned c) const { | |
return _m[r][c]; | |
} | |
private: | |
/** | |
* @brief Actual data. Note: This is NOT initialized by default! | |
*/ | |
FloatType _m[h][w]; | |
}; | |
// double matrix | |
template<unsigned w,unsigned h> class dmatrix : public matrix<double,w,h> {}; | |
// float matrix | |
template<unsigned w,unsigned h> class fmatrix : public matrix<float,w,h> {}; | |
} // end namespace NV | |
int main(void) | |
{ | |
const unsigned size = 10; | |
NV::dmatrix<size,size> m; | |
for(unsigned i = 0; i < size; i++) { | |
try { | |
m.at(i,i) = 321; | |
m(i,size-i-1) = 123; | |
} catch(std::invalid_argument& e) { | |
printf("Got Exception: %s\n",e.what()); | |
break; | |
} | |
} | |
m.print(); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment