Linker error with variable templates

202 views Asked by At

Consider the code below:

#include <iostream>

template<typename T>
T n;

int main()
{
    n<int> = 42;
    std::cout << n<int> << std::endl;
}

It compiles and links with g++5.1, and it displays 42. However, clang++ fails to link it:

undefined reference to n<int>

If I initialize the template variable like

template<typename T> T n{};

then clang++ links it too.

Any idea what's going on? Is clang++ "correct" in failing to link the program? And why does it work if I initialize the template variable?

As far as I know, template variables are just syntactic sugar for template wrappers around static members, so n<int> = 42 is effectively specializing the int instance. IMO, the code should link.

1

There are 1 answers

1
dyp On BEST ANSWER

This is a bug in clang++ #22825. The bug report has been filed on 2015-03-06 and the bug has not yet been fixed. Richard Smith supposes this definition is incorrectly treated only as a forward-declaration.