开发者

C++ Language template question

Below is a small test case that demonstrates a problem that I am trying to solve using templates in C++:

template<typename T>
void
unused(T const &) {
  /* Do nothing. */
}

int main() {
  volatile bool x = false;
  unused(!x); // type of "!x" is bool
}

As written below, the g++ v3.4.6 compiler complains:

test.cc: In constructor `test::test()':
test.cc:11: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
test.cc:3: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'

The goal here is to have unused suppress unused variable warnings that occur in optimized code. I have a macro that does an assertion check and in optimized code the assertion goes away, but I want any variables in the assertion's expression to remain referenced so that I don't get unused variable warnings only in optimized code. In the definition for unused() template function, I use a reference so that no copy constructor code gets inadvertently run so that the call to unused can be completely elided by the compiler.

For those interested, the assertion macro looks like this:

#ifdef NDEBUG
#  define Assert(expression) unused(expression)
#e开发者_开发技巧lse // not NDEBUG
#  define Assert(expression)      \
{         \
  bool test = (expression);      \
     \
  if (!test) {        \
    if (StopHere(__LINE__, __FILE__, __PRETTY_FUNCTION__,  \
                    #expression, false)) {    \
      throw Exit(-1); /* So that destructors are run. */  \
    }         \
  }         \
}
#endif // else not NDEBUG

For the above test case, I can make the error go away by adding another similar unused function like this:

template<typename T>
void
unused(T const) {
  /* Do nothing. */
}

However, then other cases calling unused() fail due to ambiguity when the argument can be made a reference to with something like:

file.h:176: error: call of overloaded `unused(bool)' is ambiguous
myAssert.h:27: note: candidates are: void unused(T) [with T = bool]
myAssert.h:34: note:                 void unused(const T&) [with T = bool]

So my question is, how can I change unused() or overload it so that it meets the following requirements:

  1. The call to unused() can be optimized away into a no-op by the compiler.
  2. It causes any variables that are present in the expression passed to unused() to appear used and thus not result in a warning about them being defined but not used.
  3. The argument to unused() may or may not be able to be referenced.
  4. The argument to unused() may be an object with an expensive copy constructor which should not be invoked when unused() is invoked.

Thanks.

-William


A common (and much simpler) way to achieve this is to just cast the result to void.

(void) x;

where x is some otherwise unreferenced value.


Charles Nicholson suggests doing something like this to mark unused variables for reasons explained in this article:

#define UNSUSED(a) ((void)sizeof(a))

The short version is... sizeof does not evaluate the expression, but compilers still count it as "used" when it's seen in this context.

I believe this satisfies all 4 of your criteria, specifically because sizeof() can take any valid expression, and because the expression will not be evaluated (and thus will not generate any code).


As Johannes said in the comments, you hit a compiler bug. You can work around it by explicitly converting to bool:

unused( bool( !readWriteActivated) ); // add bool() to any (!volatile_bool_var)

Old answer (but still not a bad idea)

If I recall the const-volatile qualification rules, all you need is to qualify the dummy variable more. Essentially, you just want to parrot the error message back in the declared type :vP .

template<typename T>
void
unused(T const volatile &) { // only change is to add "volatile"
  /* Do nothing. */
}

Also, nice that you put the const after the type, where it belongs.


The best solution that I've seen is like this:

#define UNUSED(x) ((void)x)

It is portable, and suppresses the warning successful.

EDIT:

since you've stated that this is more like an assertion, then you should probably do something like this:

#if defined ASSERT_ENABLED
#define TEST(test) (!(test)) ? assert_failed(# test, __FILE__, __LINE__) : (void)0    
#else
#define TEST(ignore) ((void)0)
#endif

This will produce no code unless ASSERT_ENABLED is defined and won't produce a warning about unused variables. This is pretty much how the assert macro in libc works.

I suppose the issue is that the variables are only used in the assertion, which is a poor way to do what you want. Why not mark it as unused and use the assertion macro separately that way it is clear that the variable isn't really used for anything, but you still get your debug build assertion. Just tackle the problems individually.


Change your definition of unused:

inline void unused(bool) {}

Since you already want an expression for which conversion to bool is required, this does that conversion and nothing else. Inline allows the compiler to optimize, including in situations where the expression doesn't have side-effects (but you'll have to test to know exactly what happens in complex situations).

Additionally, this fixes a common problem with most assert macros: if the expression does have side-effects, those will always be evaluated. (Depending on use, that can be very good or very bad.)


The compiler warning has nothing to do with used or unused. You are passing a volatile variable - readWriteActivated - to a function which does not accept a volatile reference. Try a const cast.


Why not skip templates altogether and go with the ellipses.

inline void unused (...) { /* do nothing */ }


If you want to suppress the unused variable warning, why do you call it as
unused(!readWriteActivated); ? Why can't you just call it as
unused(readWriteActivated); and make the code as

template<typename T>
void UnUsed(const T& )
{

}

For more references see the blog post from Herb Sutter Here

EDIT: Removed the parameter name in the function. This works for unused(!readWriteActivated); as well.


It is a bug:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42655

There is no work around at the unused() level. Instead, each occurrence may be worked around by introducing a temporary variable before calling unused():

template<typename T>
void
unused(T const &) {
  /* Do nothing. */
}

int main() {
  volatile bool x = false;
  bool avoidGCC42655 = !x; // type of "!x" is bool
  unused(avoidGCC42655);
}


Why are you passing !readWriteActivated instead of readWriteActivated if the value of the expression doesn't matter?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜