Search code examples
c++pointerscastingshared-ptrsmart-pointers

Cannot convert from std::shared_ptr<_Ty> to std::shared_ptr<_Ty>


I am getting the following error:

error C2440: 'static_cast' : cannot convert from 'std::shared_ptr<_Ty>' to 'std::shared_ptr<_Ty> stack\genericstack.h 36 1 Stack

GenericStack.h

#ifndef _GENERIC_STACK_TROFIMOV_H_
#define _GENERIC_STACK_TROFIMOV_H_

#include <memory>

class GenericStack {
    struct StackNode {
        std::shared_ptr<void> _data; 
        StackNode* _next;
        StackNode(const std::shared_ptr<void>& data, StackNode* next) 
            : _data(data), _next(next) {

        }
    };

    StackNode* _top; 

    GenericStack(const GenericStack&);
    GenericStack& operator=(const GenericStack&);

protected:
    GenericStack();
    ~GenericStack();
    void push(const std::shared_ptr<void>&);
    void pop();
    std::shared_ptr<void>& top();
    bool isEmpty() const;
};

template <class T>
class TStack: private GenericStack {                  
public:
    void push(const std::shared_ptr<T>& p) { GenericStack::push(p); }
    void pop() { GenericStack::pop(); }
    std::shared_ptr<T> top() { return static_cast<std::shared_ptr<T>>(GenericStack::top()); }
    bool empty() const { return GenericStack::isEmpty(); }
};

#endif

GenerickStack.cpp

#include "GenericStack.h"

GenericStack::GenericStack()
    :_top(0) {

};
GenericStack::~GenericStack() {
    while(!isEmpty()) {
        pop();
    }
};

void GenericStack::push(const std::shared_ptr<void>& element) {
    _top = new StackNode(element, _top);
}

std::shared_ptr<void>& GenericStack::top() {
    return _top->_data;
}
void GenericStack::pop() {
    StackNode* t = _top->_next;
    delete _top;
    _top = t;
}

bool GenericStack::isEmpty() const {
    return !_top;
}

Main.cpp

#include <iostream>
#include "GenericStack.h"

int main() {
    TStack<int> gs;

    std::shared_ptr<int> sh(new int(7));
    gs.push(sh);
    std::cout << *gs.top() << std::endl;

    return 0;
}

Why am I getting the error?

I would expect the cast to happen successfully, since with raw pointers I always can case from void* to the real type pointer.

What I want to do here is to create a stack template. But I am trying to reuse as much code as I can, so that templated classes would not swell too much.

Thank you.


Solution

  • You get that error because static_cast requires the types from and to to be convertible. For shared_ptr that will hold only if c'tor overload 9 would participate in overload resolution. But it doesn't, because void* is not implicitly convertible to other object pointer types in C++, it needs an explicit static_cast.

    If you want to convert shared pointers based on static_casting the managed pointer types, you need to use std::static_pointer_cast, that is what it's for.

    So after plugging that fix

     std::shared_ptr<T> top() { return std::static_pointer_cast<T>(GenericStack::top()); }
    

    Your thin template wrapper will build fine.