Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
Cavaz Avatar asked Nov 07 '12 16:11

Cavaz


People also ask

What is macro template macro expansion?

Notes. Here, SIZE and X are called as 'macro templates', whereas, 5 and 5+5 are called their corresponding 'macro expansions'. A macro template and its macro expansion are separated by blanks or tabs. A space between # and define is optional. A macro definition is never to be terminated by a semicolon.

What is a template macro?

A macro is a recording of formatting changes and other steps that can be replayed quickly. A template is a pre-formatted spreadsheet with headers and formulas – awaiting your data.

Are templates more efficient than macros?

The results show that for this example, compiling templates is faster than the equivalent macro version! On top of that, templates are more maintainable, since the code is not duplicated, and the compiler can give better error messages.

What is meant by macro expansion?

In computer programming, a macro (short for "macro instruction"; from Greek μακρο- 'long, large') is a rule or pattern that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is known as macro expansion.


1 Answers

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.

like image 75
Lightness Races in Orbit Avatar answered Oct 22 '22 14:10

Lightness Races in Orbit