Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using __LINE__ macro as a template parameter in visual studio

I expected the following code to work, but I received a compile 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 does this happen? I though __LINE__ would paste in the line number before template instantiation occurred?

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

like image 482
Bob Avatar asked Mar 22 '11 21:03

Bob


2 Answers

Works for me in VS 2010 10.0.40219.1 SP1Rel and in Ideone

But MSDN mentions problems which result in C2975, if using __LINE__ in template with compiler-option /ZI: MSDN C2975

Edit: Sorry, I linked the german version, here in english

like image 166
MacGucky Avatar answered Sep 22 '22 04:09

MacGucky


For what it's worth, this is suppose to be valid code. __LINE__ is suppose to behave as if it were:

#define __LINE__ 0

Of course, replacing 0 with the current line number.

like image 23
2 revs Avatar answered Sep 19 '22 04:09

2 revs