Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable and template specialization ambiguity

Tags:

c++

The FQA poses this code example:

#include <cstdio>
template<int n> struct confusing
{
    static int q;
};
template<> struct confusing<1>
{
    template<int n>
    struct q
    {
        q(int x)
        {
            printf("Separated syntax and semantics.\n");
        }
        operator int () { return 0; }
    };
};
char x;
int main()
{
    int x = confusing< SOME_NUMBER_HERE >::q < 3 > (2);
    return 0;
}

q either refers to static int q or q(int x) depending on the value of SOME_NUMBER_HERE. It seems like a fairly contrived example considering q can simply be named something else. gcc even has a warning:

warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]

     int x = confusing<2>::q < 3 > (2);

Is there a practical scenario where this kind of thing is a problem?


1 Answers

I haven't seen any but, of course, that does not prove that there are real world examples.

I remember that Andrei Alexandrescu gave a talk about static_if (slides). I think he also addressed template hijacking, which is similar to your example.

Well, if someone can come up with a real example, I'm quite sure that Andrei Alexandrescu is the one. :-)

like image 188
Philipp Claßen Avatar answered Mar 13 '26 20:03

Philipp Claßen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!