Assert::AreEqual format message in one line

assert, c++, visual-studio-2012

Solution

If you don't mind using macros:

#define MSG(msg) [&]{ std::wstringstream _s; _s << msg; return _s.str(); }().c_str()

Use it like this:

Assert::AreEqual(42, my_value_to_verify, MSG("Value " << i << " failed"));

Note that the `c_str()` at the end must be outside the lambda — `str()` returns a copy of the original stream's contents so they will survive the destruction of `_s`, but `c_str()` returns a pointer to an internal buffer and so would not survive the return from the lambda.

Note also that because streams are being used you can put any object you like in the message provided there's a corresponding `operator<<` overload, not just primitive types like `int`.

Problem

Update 3: This page shows me how to do it in three lines. Anyone know how it can be done in one line? ``` for (int i = 0; i < 5; i++) { my_value_to_verify = get_my_values(i); wchar_t message[200]; // Line 1 _swprintf(message, L"Value %d failed", i); // Line 2 Assert::AreEqual(42, my_value_to_verify, message); // Line 3 } ``` Update 2 As pointed out by @JaredPar, the documentation I had been referring to was actually for C++/CLI. After additional searching, it looks like the following link contains reference to the function I am working with. Update 1 Removing the brackets from {i} also still results in a compilation error: ``` Error: no instance of overloaded function ...AreEqual matches the argument list (int, int, const wchar_t[16], int) ``` Original Post Using Microsoft documentation I'm trying to construct an Assert statement that will print a formatted message. For example: ``` for (int i = 0; i < 5; i++) { my_value_to_verify = get_my_values(i); Assert::AreEqual(42, my_value_to_verify, L"Value %d failed", {i}); } ``` If you can, ignore everything else expect that I am trying to print the value of i in the assert statement. The last parameter "{i}" is supposed to be an array - I am trying to follow what the documentation states. However, I receive a compilation error when doing it this way. ``` (231): error C2143: syntax error : missing ')' before '{' (231): error C2059: syntax error : ')' (231): error C2143: syntax error : missing ';' before '{' (231): error C2143: syntax error : missing ';' before '}' ``` I'm getting tripped up on how to declare the array in order to format the message. How should this array be declared in my case? Can it be done inside the Assert statement?

Original source