Using __LINE__ macro as a template parameter in visual studio

I expected the following code to work, but I got a compilation error:

error C2975: 'n' : invalid template argument for 'foo', expected compile-time constant expression 
 #include <iostream> using namespace std; template<int N> struct foo { foo() { cout << N << endl; } }; int main() { foo< __LINE__ > f; } 

Why is this happening? Although I __LINE__ would insert a line number before creating the template?

If I wanted to do this, should I just enter static const int to store the line number or is there a standard solution?

+6
c ++ visual-studio
source share
3 answers

Works for me in VS 2010 10.0.40219.1 SP1Rel and in Ideone

But MSDN mentions the problems that lead to C2975 if you use __LINE__ in the template with the /ZI compiler option: MSDN C2975

Edit: Sorry, I linked the German version here in English

+11
source share

For what it's worth, it's valid to be a valid code. __LINE__ should behave as if:

 #define __LINE__ 0 

Of course, replacing 0 with the current line number.

+2
source share

@Bob, you will like this one!

I was interested in your question, so I tried my code. It compiled in g ++, but not with your error in MSVC10. To research, I used Google to find out how to see the output of the preprocessor: you set the parameter "Properties | C ++ | Preprocessor | Preprocess to file" to true. And then I put it together again ... AND THIS WORK! It turns out that if this option is disabled, compilation fails; if it is enabled, compilation works. I believe that MS is not trying to generate LINE records unless the preprocessor output is captured. Oy va voy!

0
source share

All Articles