Reputation: 10103
I have a bunch tests for a project which were originally written using Gtest, but I have since moved them into Microsoft's CppUnitTestFramework. In order to prevent having to rewrite all my tests, I made macros which follows how GTest does its tests -- for example, EXPECT_EQ
.
Now, I am trying to eliminate all warnings generated by MsBuild, including those by the Code Analysis, which relate to using constexpr
if available. In the tests, there's quite a few of these, since the expected value is usually a literal, although not always. So I have my own EXPECT_EQ
which is as follows:
#define EXPECT_EQ( x, y ) { const auto _x = (x); const auto _y = (y); if ( _x == _y ) {} else { Assert::Fail(createFailMessage( _x, L" == ", _y ).c_str(), LINE_INFO() ); } }
This works fine; however, if it is called with EXPECT_EQ( 7, getTime() )
, then I get a warning about how _x
can be constexpr
.
I know I can just create a separate macro like so:
#define EXPECT_CEQ( x, y ) { constexpr auto _x = (x); const auto _y = (y); if ( _x == _y ) {} else { Assert::Fail(createFailMessage( _x, L" == ", _y ).c_str(), LINE_INFO() ); } }
However, if I go back to GTest later, then I would have to fix all my tests to change EXPECT_CEQ
to EXPECT_EQ
.
So, my question is, is it possible to combine these two macros to make _x
conditionally constexpr
based on whether or not it can be constexpr
?
PS: Yes, I know, macros bad.
Upvotes: 2
Views: 164
Reputation: 26362
One possible solution is to use a lambda that is invoked immediately:
const auto _x = [&]{ return (x); }();
[&]
will capture every variable that might be used in the x
expression.
Upvotes: 3