Skip to content

Instantly share code, notes, and snippets.

@PureAbstract
Created September 17, 2013 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PureAbstract/6601192 to your computer and use it in GitHub Desktop.
Save PureAbstract/6601192 to your computer and use it in GitHub Desktop.
Try and show how toString and StringMaker interact.
// ==================== 1) Overload Catch::toString
struct ts_overload { }; // have an overload of toString
namespace Catch {
std::string toString( const ts_overload& )
{
return "ts:ts_overload";
}
}
TEST_CASE( "toString : ts_overload" )
{
// Passes. Obviously!
REQUIRE( Catch::toString( ts_overload() ) == "ts:ts_overload" );
}
TEST_CASE( "toString : vector<ts_overload>" )
{
typedef std::vector<ts_overload> vec_type;
// Fails - uses the 'default toString {?}
REQUIRE( Catch::toString( vec_type(1) ) == "{ ts:ts_overload }" );
}
// ==================== 2) Specialise Catch::StringMaker
struct sm_spec { }; // has a specialisation of StringMaker
namespace Catch {
template<>
struct StringMaker<sm_spec> {
static std::string convert( const sm_spec& )
{
return "sm:sm_spec";
}
};
};
TEST_CASE( "toString : sm_spec" )
{
// Invoked the toString<T> templace, which then invokes
// StringMaker<sm_spec> - so that's fine
REQUIRE( Catch::toString( sm_spec() ) == "sm:sm_spec" );
}
TEST_CASE( "toString : vector<sm_spec>" )
{
typedef std::vector<sm_spec> vec_type;
// vector's StringMaker calls toString, which invokes StringMaker<T>,
// which does the right thing
REQUIRE( Catch::toString( vec_type(1) ) == "{ sm:sm_spec }" );
}
// ==================== 3) overload toString AND specialise StringMaker
struct sm_both { };
namespace Catch {
std::string toString( const sm_both& ) {
return "ts:sm_both";
}
template<>
struct StringMaker<sm_both> {
static std::string convert( const sm_both& ) {
return "sm:sm_both";
}
};
}
TEST_CASE( "toString : sm_both" )
{
// Invoked the toString<T> overload
REQUIRE( Catch::toString( sm_both() ) == "ts:sm_both" );
}
TEST_CASE( "toString : vector<sm_both>" )
{
typedef std::vector<sm_both> vec_type;
// vector's StringMaker calls the template toString - NOT the
// overload, which invokes StringMaker<sm_both>
REQUIRE( Catch::toString( vec_type(1) ) == "{ sm:sm_both }" );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment