samedi 30 juillet 2022

C++ Optional

can I use Optional<Parent Class pointer> Map as function parameter while passing Optional<Child Class pointer> Map as argument?

For example, I have two classes and a map

#include <iostream>
#include <string>
#include <optional>
#include <map>
#include <memory>

using namespace std;

class A {
    public:
       virtual void f() = 0;
}; //abstract class

class B : public A {
    public:
       void f() override {
           std::cout <<"override only" << std::endl;
       }
};

void testFunction(std::map<int, std::optional<std::shared_ptr<B>>>) {
    std::cout << "success!" << std::endl;
}

int main() {
    std::map<int, std::optional<std::shared_ptr<A>>> map;
    testFunction(map);
    return 0;
}

code link: When I want to pass map to testFunction, compiler throws "no conversion" error.

main.cpp:27:18: error: could not convert ‘map’ from ‘map<[...],optional>>’ to ‘map<[...],optional>>’

Is it because of the Optional or Map? (I think it's map, because map<int, Parent Class> doesn't work neither.

Is there a way to pass a map with optional of child class pointer?

Thanks!

=======

Or let's talk about a simpler version, we only have pointer in the map, is there a way to achieve below codes:

void testFunction(std::map<int, std::shared_ptr<B>>) {
    std::cout << "success!" << std::endl;
}

int main() {
    std::map<int, std::shared_ptr<A>> map;
    testFunction(map);
}

Aucun commentaire:

Enregistrer un commentaire