Browse Source

Make Math::pow() templated on type.

vectorfields
Vladimír Vondruš 14 years ago
parent
commit
925cc3d2ff
  1. 19
      src/Math/Math.h
  2. 5
      src/Math/Test/MathTest.cpp

19
src/Math/Math.h

@ -52,6 +52,17 @@ template<> struct Constants<float> {
static constexpr float Sqrt2 = 1.41421356237f; static constexpr float Sqrt2 = 1.41421356237f;
static constexpr float Sqrt3 = 1.73205080757f; static constexpr float Sqrt3 = 1.73205080757f;
}; };
namespace Implementation {
template<size_t exponent> struct Pow {
template<class T> inline constexpr T operator()(T base) const {
return base*Pow<exponent-1>()(base);
}
};
template<> struct Pow<0> {
template<class T> inline constexpr T operator()(T base) const { return 1; }
};
}
#endif #endif
/** /**
@ -59,14 +70,10 @@ template<> struct Constants<float> {
* *
* Returns integral power of base to the exponent. * Returns integral power of base to the exponent.
*/ */
template<size_t exponent> inline constexpr size_t pow(size_t base) { template<size_t exponent, class T> inline constexpr T pow(T base) {
return base*pow<exponent-1>(base); return Implementation::Pow<exponent>()(base);
} }
#ifndef DOXYGEN_GENERATING_OUTPUT
template<> inline constexpr size_t pow<0>(size_t base) { return 1; }
#endif
/** /**
* @brief Integral logarithm * @brief Integral logarithm
* *

5
src/Math/Test/MathTest.cpp

@ -30,8 +30,9 @@ void MathTest::degrad() {
} }
void MathTest::pow() { void MathTest::pow() {
QCOMPARE(Math::pow<10>(2), 1024ul); QCOMPARE(Math::pow<10>(2ul), 1024ul);
QCOMPARE(Math::pow<0>(3), 1ul); QCOMPARE(Math::pow<0>(3ul), 1ul);
QCOMPARE(Math::pow<2>(2.0f), 4.0f);
} }
void MathTest::log() { void MathTest::log() {

Loading…
Cancel
Save