gaazkam gaazkam - 1 year ago 115
C++ Question

Why can't I use assert with std::is_same?

Can somebody explain to me why on Earth does this code snippet refuse to work?

#include <cassert>
#include <type_traits>
using namespace std;

int main()
assert(is_same<int, int>::value);

Compilation fails because, according to the compiler:

prog.cpp:7:33: error: macro "assert" passed 2 arguments, but takes just 1
assert(is_same<int, int>::value);
prog.cpp: In function 'int main()':
prog.cpp:7:2: error: 'assert' was not declared in this scope
assert(is_same<int, int>::value);

is_same<int, int>::value
is undoubtedly one argument. Also
is declared at this scope, and the compiler itself confirmed it in the previous error!

Answer Source

The macro splits your parameter(s) like this:

    is_same<int , int>::value
 // ^^ par1  ^^// ^^ par2  ^^

As assert() is a macro definition (with one parameter), it's handled by the C-preprocessor. The preprocessor is unaware of c++ syntax like template parameters gouped in angle brackets (<>) separated with ,. So the parameter expression is split up like shown above.

You can avoid that using extra parenthesis, so the C-preprocessor will take that parameter as a whole:

assert((is_same<int, int>::value));
    // ^                        ^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download