Ishan Bhatnagar
Ishan Bhatnagar

Reputation: 13

Member function of a templated class can't return a pointer to member structure?

This code doesn't compile (gives errors C2059, C2065, C2072, C2143, C2146, C2447, C2470, C4430) But does if you change B* to an inbuild type like int. Any ideas?

template <typename T>
class A
{
private:
    struct B
    {
        T key;
    };

    B* foobar(T key);

};

template <typename T>
B* A<T>::foobar(T key) 
{
    B* ptr = new B;
    B->key = key;
    return ptr;
}

int main()
{}

Upvotes: 1

Views: 81

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361802

The return type should be typename A<T>::B*, not just B*:

template<typename T>
typename A<T>::B* A<T>::foobar(T key)
{
   //..
}

Note also typename keyword in the return type.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227608

You have a few errors in your method.

1) the return type's scope must be properly qualified.

2) You have to set the key if a A::<T>::B instance, not a B.

Try this:

template <typename T>
typename A<T>::B* A<T>::foobar(T key) // fix error 1)
{
    B* ptr = new B();
    ptr->key = key;  // fix error 2)
    return ptr;
}

Upvotes: 4

Related Questions