This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Arithmetic type emulator helper class for testcases.
- From: "Chris Fairles" <chris dot fairles at gmail dot com>
- To: libstdc++ <libstdc++ at gcc dot gnu dot org>
- Date: Fri, 11 Jul 2008 08:48:33 -0400
- Subject: Arithmetic type emulator helper class for testcases.
I'm writing some testcases for my <chrono> (i.e. duration and
time_point) impl. For duration, the standard allows the repesentation
to be a class that emulates an arithmetic type. I wrote up the
following helper class (not all operators are shown for brevity):
template<typename T>
struct type_emulator
{
type_emulator() : i(T(0)) { }
type_emulator(T j) : i(j) { }
type_emulator(const type_emulator& e) : i(e.i) { }
type_emulator(type_emulator&& e) : i(std::move(e.i)) { }
type_emulator& operator*=(type_emulator a)
{ i *= a.i; return *this; }
type_emulator& operator+=(type_emulator a)
{ i += a.i; return *this; }
operator T () { return i; }
T i;
};
template<typename T>
bool operator==(type_emulator<T> a, type_emulator<T> b)
{ return a.i == b.i; }
template<typename T>
bool operator<(type_emulator<T> a, type_emulator<T> b)
{ return a.i < b.i; }
template<typename T>
type_emulator<T> operator+(type_emulator<T> a, type_emulator<T> b)
{ return a += b; }
template<typename T>
type_emulator<T> operator*(type_emulator<T> a, type_emulator<T> b)
{ return a *= b; }
namespace std
{
template<typename T, typename U>
struct common_type<type_emulator<T>, U>
{ typedef typename common_type<T,U>::type type; };
template<typename T, typename U>
struct common_type<U, type_emulator<T>>
{ typedef typename common_type<U,T>::type type; };
template<typename T, typename U>
struct common_type<type_emulator<T>, type_emulator<U>>
{ typedef typename common_type<T,U>::type type; };
namespace chrono
{
template<typename T>
struct treat_as_floating_point<type_emulator<T>>
: is_floating_point<T>
{ };
}
}
typedef type_emulator<int> int_emulator;
typedef type_emulator<double> dbl_emulator;
This allows me to test things like:
duration<dbl_emulator, std::micro> d4(5.0);
duration<dbl_emulator, std::milli> d4_copy(d4);
VERIFY(d4.count() == d4_copy.count() * dbl_emulator(1000.0));
etc...
Since I need it in several test case files, can it be placed in one of
the util headers? Does it seem like something useful outside of
duration testing? Maybe something similar already exists (I looked in
all the util headers I think and didn't see anything sufficient)?
Chris