views:

62

answers:

1

I've recently started reading Modern C++ Design by Andrei Alexandrescu. After reading Compile-Time Assertions, I tried the following code:

template<bool> struct CompileTimeChecker
{
    CompileTimeChecker(...){};
};
template<> struct CompileTimeChecker<false>{};

#define STATIC_CHECK(expr, msg) \
{\
    class ERROR_##msg{}; \
    (void)sizeof(CompileTimeChecker<(expr)!=0>((ERROR_##msg())));   /*Line 1*/ }


int main()
{
    STATIC_CHECK(sizeof(char)>sizeof(int),TypeTooNarrow); /*Line 2*/

    STATIC_CHECK(sizeof(char)<sizeof(int),TypeTooNarrow); /*Line 3*/
}

The code should not compile due to Line 2, but it compiles fine. If I change the Line 1 to

(void)(CompileTimeChecker<(expr)!=0>((ERROR_##msg())));   /*Line 1*/ }

or

new CompileTimeChecker<(expr)!=0>((ERROR_##msg()));   /* Line 1*/ }

it works as expected. I don't get it.

+1  A: 

Try updated version from the Loki library.

Nikolai N Fetissov
@Nikolai: That works. In that code, what's the need for (void)Error_##msg;
Saurabh Manchanda
That second statement is there, I'm guessing, so compiler does not complain about unused variable.
Nikolai N Fetissov
Ok. And do you have anything on the question I actually asked?
Saurabh Manchanda
GCC 4.2.1 says this: `error: invalid application of ‘sizeof’ to a function type` about both lines in `main()`, i.e. expanded macro is interpreted as function declaration. That's what the comments in the code I linked to also suggest. Your compiler could be just cheating and skipping the `(void)sizeof(...);` line. Also, the Loki library - all the code from the book and more - wasn't fully compilable by any existing compiler at the time the book was written.
Nikolai N Fetissov
Hmmm.. Thanks..
Saurabh Manchanda
What compiler are you using?
Nikolai N Fetissov
I'm using GCC 4.5.0
Saurabh Manchanda