简体   繁体   中英

Status of inconsistent template specializations across translation units?

Please consider the below program:

FILE AH

template <typename T> struct C { static constexpr int x = 42; };

FILE BH

#include "A.H"

template <> struct C<int> { static constexpr int x = 43; };

FILE A.CC

#include "A.H"

void a() { std::cout << C<int>::x; }

FILE B.CC

#include "B.H"

void b() { std::cout << C<int>::x; }

FILE MAIN.CC

void a(); void b();

int main() { a(); b(); }

What is the status of this program? Is it ill-formed, ill-formed with no diagnostic required, does it exhibit undefined behaviour, or none of the above (its okay)?

If none of the above, what is the output of the program?

If one of the above, what rule does it violate?

(Also, would the answer be different if BH contained a partial specialization rather than an explicit specialization?)

This is [temp.arg.template]/2 :

If a specialization is not visible at the point of instantiation, and it would have been selected had it been visible, the program is ill-formed, no diagnostic required.

The specialization for C<int> isn't visible in the definition of a() , but would've been selected if it had been.


But more importantly, this is the limerick (spacing mine):

When writing a specialization,
be careful about its location;
or to make it compile
will be such a trial
as to kindle its self-immolation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM