catch2/docs/tostring.md

47 lines
1.7 KiB
Markdown
Raw Normal View History

2014-12-09 19:54:35 +01:00
# String conversions
Catch needs to be able to convert types you use in assertions and logging expressions into strings (for logging and reporting purposes).
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.
## operator << overload for std::ostream
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:
2014-12-12 09:29:21 +01:00
```
std::ostream& operator << ( std::ostream& os, T const& value ) {
2014-12-09 19:54:35 +01:00
os << convertMyTypeToString( value );
return os;
2014-12-12 09:29:21 +01:00
}
```
2014-12-09 19:54:35 +01:00
(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).
You should put this function in the same namespace as your type.
Alternatively you may prefer to write it as a member function:
2014-12-12 09:29:21 +01:00
```
std::ostream& T::operator << ( std::ostream& os ) const {
2014-12-09 19:54:35 +01:00
os << convertMyTypeToString( *this );
return os;
2014-12-12 09:29:21 +01:00
}
```
2014-12-09 19:54:35 +01:00
## Catch::toString overload
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.
2014-12-12 09:29:21 +01:00
```
namespace Catch {
2014-12-09 19:54:35 +01:00
std::string toString( T const& value ) {
return convertMyTypeToString( value );
}
}
2014-12-12 09:29:21 +01:00
```
2014-12-09 19:54:35 +01:00
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.
---
[Home](Readme.md)