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()
{}

preguntado el 29 de julio de 12 a las 09:07

2 Respuestas

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 si un A::<T>::B ejemplo, no un B.

Prueba esto:

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;
}

Respondido 29 Jul 12, 09:07

What is the significance of new B() ? Are we calling the default initialiser? Is there any difference wrt to just 'new B'? - Ishan Bhatnagar

@IshanBhatnagar in this case there is no difference. You can use new B, which also calls the default constructor. - juanchopanza

El tipo de retorno debe ser typename A<T>::B*, No sólo B*:

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

Tenga en cuenta también typename keyword in the return type.

Respondido 29 Jul 12, 09:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.