blob: 05a6b79b9f8caf724c8ee9173aa6d55dae55388f [file] [log] [blame] [view]
Phil Nash27ce70c2014-12-09 18:54:35 +00001# String conversions
2
3Catch needs to be able to convert types you use in assertions and logging expressions into strings (for logging and reporting purposes).
Martin Hořeňovský31f5e2e2017-05-16 13:38:52 +02004Most built-in or std types are supported out of the box but there are two ways that you can tell Catch how to convert your own types (or other, third-party types) into strings.
Phil Nash27ce70c2014-12-09 18:54:35 +00005
6## operator << overload for std::ostream
7
8This is the standard way of providing string conversions in C++ - and the chances are you may already provide this for your own purposes. If you're not familiar with this idiom it involves writing a free function of the form:
9
Phil Nash82754c12014-12-12 08:29:21 +000010```
11std::ostream& operator << ( std::ostream& os, T const& value ) {
Phil Nash27ce70c2014-12-09 18:54:35 +000012 os << convertMyTypeToString( value );
13 return os;
Phil Nash82754c12014-12-12 08:29:21 +000014}
15```
Phil Nash27ce70c2014-12-09 18:54:35 +000016
17(where ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable - it doesn't have to be in another function).
18
Martin Hořeňovský31f5e2e2017-05-16 13:38:52 +020019You should put this function in the same namespace as your type and have it declared before including Catch's header.
Phil Nash27ce70c2014-12-09 18:54:35 +000020
Phil Nash605d8702015-05-20 18:12:40 +010021## Catch::StringMaker<T> specialisation
Martin Hořeňovský31f5e2e2017-05-16 13:38:52 +020022If you don't want to provide an ```operator <<``` overload, or you want to convert your type differently for testing purposes, you can provide a specialization for `Catch::StringMaker<T>`:
Phil Nash605d8702015-05-20 18:12:40 +010023
24```
25namespace Catch {
Martin Hořeňovský31f5e2e2017-05-16 13:38:52 +020026 template<>
27 struct StringMaker<T> {
Martin Hořeňovský67914d82017-05-21 23:40:05 +020028 static std::string convert( T const& value ) {
Martin Hořeňovský31f5e2e2017-05-16 13:38:52 +020029 return convertMyTypeToString( value );
30 }
31 };
Phil Nash605d8702015-05-20 18:12:40 +010032}
33```
34
Phil Nasha49f0882015-11-18 08:39:21 +000035## Exceptions
36
37By default all exceptions deriving from `std::exception` will be translated to strings by calling the `what()` method. For exception types that do not derive from `std::exception` - or if `what()` does not return a suitable string - use `CATCH_TRANSLATE_EXCEPTION`. This defines a function that takes your exception type, by reference, and returns a string. It can appear anywhere in the code - it doesn't have to be in the same translation unit. For example:
38
39```
40CATCH_TRANSLATE_EXCEPTION( MyType& ex ) {
41 return ex.message();
42}
43```
44
Phil Nash27ce70c2014-12-09 18:54:35 +000045---
46
47[Home](Readme.md)