Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ doesn't compile certain nested templates

When BREAK is defined, g++ 4.7.2 will not compile the following, which I think is valid C++. It does compile with BREAK defined if the A<U> tmp is changed to something else, like A<int> tmp - while that makes the minimal test case here work, it's no good in my actual application. Is there anything here that is not legal C++?

template <typename T>
class B {

};

template <typename T>
class A {
public:
    template <typename U> B<U> *alloc_B( );
};

template <typename T> template <typename U>
B<U> *A<T>::alloc_B( ) {
    return new B<U>( );
}

#ifdef BREAK
template <typename T>
class C {
public:
    template <typename U> void x(B<U> &b) {
        A<U> tmp;
        B<U> *tmp2;
        tmp2 = tmp.alloc_B<U>( );
        delete tmp2;
    }
};
#endif

int main( ) {
    A<int> a;
    B<float> *bp = a.alloc_B<float>( );
    delete bp;

#ifdef BREAK
    C<int> c;
    B<float> b;

    c.x(b);
#endif
}
like image 338
Andrew A Avatar asked Feb 17 '26 02:02

Andrew A


1 Answers

The alloc_B function template is a dependent name. You must call it as so:

tmp2 = tmp.template alloc_B<U>( );

That's the problem, and that is why it works when you use A<int>, because the type no longer depends on the template argument U.

like image 195
Mikael Persson Avatar answered Feb 18 '26 16:02

Mikael Persson



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!