jeudi 16 mars 2023

shared_ptr to templated base classes

I'm running into the following compilation issue with shared_ptr to templated base classes. I'm wondering why int cannot be deduced in this case from D? Does this have anything to do with the general case where D might be derived from B<int> and B<float> for example not being well formed?

#include <memory>
template <typename T>
struct B {
    virtual void foo() = 0;
};

struct D  : B<int> {
    void foo() override {}
};

template <typename T>
void func(std::shared_ptr<B<T>> sp) {

}

int main() {
    func(std::make_shared<D>());
}
<source>:17:5: error: no matching function for call to 'func'
    func(std::make_shared<D>());
    ^~~~
<source>:12:6: note: candidate template ignored: could not match 'B<type-parameter-0-0>' against 'D'
void func(std::shared_ptr<B<T>> sp) {
     ^
1 error generated.
Compiler returned: 1

The following works fine

#include <memory>
template <typename T>
struct B {
    virtual void foo() = 0;
};

struct D  : B<int> {
    void foo() override {}
};

template <typename T>
void func(B<T> * sp) {

}

int main() {
    func(new D);
}

Aucun commentaire:

Enregistrer un commentaire