简体   繁体   中英

macro expansion with templates

I'm writing several functions which takes as input the result of a template function:

int alg1(Vect3) {...}
...
int algN(Vect3) {...}

void main() {
    alg1( mat.topRightCorner<3,1>() )
}

where, if you are curious, topRightCorner returns a submatrix of mat , a method from the Eigen , where the dimension are placed as template parameters when are known at compile time.

However creating a "shortcut" using a macro to quickly switch between different algorithms (since in the real code the function is called many times), like this

#define ALG(X)    ( algN(X) )

ALG( mat.topRightCorner<3,1>() )

gives an error, since the macro is correctly expanded but is somehow misinterpreted as with two different parameters, mat.topRightCorner<3 and 1>() .

Wrapping the input with brackets will do the trick, but why this behaviour?

Because , is accepted by the preprocessor as a delimiter for a new macro argument, and because the preprocessor doesn't really care that you might have instead meant it as a delimiter for a template parameter list.

To be slightly more precise:

ALG( mat.topRightCorner<3,1>() )
     ^^^^^^^^^^^^^^^^^^^^ ^^^^

Both of these lexically look like valid macro arguments, and macro parsing takes priority.

On the other hand, the preprocessor is aware of what () does, so you can "force" parsing as a single argument that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM