| Phil Nash | 27ce70c | 2014-12-09 18:54:35 +0000 | [diff] [blame^] | 1 | # String conversions |
| 2 | |
| 3 | Catch needs to be able to convert types you use in assertions and logging expressions into strings (for logging and reporting purposes). |
| 4 | Most 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. |
| 5 | |
| 6 | ## operator << overload for std::ostream |
| 7 | |
| 8 | This 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 | |
| 10 | ```std::ostream& operator << ( std::ostream& os, T const& value ) { |
| 11 | os << convertMyTypeToString( value ); |
| 12 | return os; |
| 13 | }``` |
| 14 | |
| 15 | (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). |
| 16 | |
| 17 | You should put this function in the same namespace as your type. |
| 18 | |
| 19 | Alternatively you may prefer to write it as a member function: |
| 20 | |
| 21 | ```std::ostream& T::operator << ( std::ostream& os ) const { |
| 22 | os << convertMyTypeToString( *this ); |
| 23 | return os; |
| 24 | }``` |
| 25 | |
| 26 | ## Catch::toString overload |
| 27 | |
| 28 | If you don't want to provide an ```operator <<``` overload, or you want to convert your type differently for testing purposes, you can provide an overload for ```Catch::toString()``` for your type. |
| 29 | |
| 30 | ```namespace Catch { |
| 31 | std::string toString( T const& value ) { |
| 32 | return convertMyTypeToString( value ); |
| 33 | } |
| 34 | } |
| 35 | }``` |
| 36 | |
| 37 | Again ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable. Note that the function must be in the Catch namespace, which itself must be in the global namespace. |
| 38 | |
| 39 | --- |
| 40 | |
| 41 | [Home](Readme.md) |