Problems with templates and __LINE__

I am working on some code that I would like to integrate into the library. I would like it to have no external dependencies and conform to standards. I want to use a template to create a unique type that allows me to check the type of compilation time.

Update:
The code below is from msdn, this is not what I'm trying to do. I am trying to use a template to have a unique type every time the user creates it using a macro. In this way, you can check the compilation time so that the types do not mix. I am working on the code from this article: http://www.artima.com/cppsource/safelabels.html and yes, I know about the existence of std :: bitset thanks.

As Tony noted, __LINE__it is not a reliable guarantee of uniqueness.

I encountered the following error:

http://msdn.microsoft.com/en-us/library/kyf0z2ka%28v=VS.100%29.aspx

C2975 will also occur when you use `__LINE__` as a compile-time constant with /ZI:

// C2975b.cpp
// compile with: /ZI
// processor: x86
template<long line> 
void test(void) {}

int main() {
    test<__LINE__>();   // C2975
    test<__LINE__>();   // OK
}

Compiling without / ZI is good, but it is installed by default in msvc, and I don’t assume that all users of my library are first launched into compiler errors until I tell them to enable this switch.

How would you deal with this problem?

The only realistic idea that I still check for msvc and then use __COUNTER__for msvc ...

update:
Actually it __COUNTER__doesn’t work, because I need the types to be unique in each declaration, but for different translation units they must be the same, otherwise I get problems with the linker of unresolved external links.

+3
1

. , :

namespace { struct unique_type {}; }
template<typename T> int foo() { return 42; }
static int bar = foo<unique_type>();

foo<unique_type>() . __LINE__ - MSVC:

namespace {
    struct unique_type{};
    const int LINE = __LINE__;
}
template<typename T, int N> int foo() { return 42; }
static int bar = foo<unique_type, LINE>();
+3

Source: https://habr.com/ru/post/1773732/


All Articles