29 December 2011

Using C++11 std::tuple

A snippet of C++ unit test code showing how to use std::tuple. Using enums to help index the std::get function that is used to retrieve tuple values. Note that std::tuple_size class is used to get the value (size) of the typedef Tuple_t.

 #include <UnitTest++.h>  
#include <tuple>
SUITE(TUPLES){
TEST(Tuples) {
enum TupleIndex {MEAN, STDDEV, SIZE};
typedef std::tuple<double,double> Tuple_t;
CHECK_EQUAL( SIZE, std::tuple_size<Tuple_t>::value );

Tuple_t T1( 99.0, 0.5);
CHECK_CLOSE( 99.0, std::get<MEAN >(T1), 1e-09);
CHECK_CLOSE( 0.5, std::get<STDDEV>(T1), 1e-09);
#if 0
//Out of Range ... caught at compile time.
//g++ error message not so helpful.
std::get<SIZE>(T1);
#endif
}
}

No comments: