Tutorial :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)  #else // 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. */  \      }         \    }         \  }  

Next Post »