mercredi 5 avril 2023

lambda return type restriction for C++11 [duplicate]

So i am working on a C++11 project and i have class structure something like this

header file

class AgentClassInterface {
public:
    virtual void doSomething() = 0;
};
class AgentClass : public AgentClassInterface {
public:
    void doSomething() {};
    AgentClass() = default;
    virtual ~AgentClass() = default;
    static std::shared_ptr<AgentClass> create();
};

using SetUpFunctionTest =
    std::function<std::pair<bool, std::shared_ptr<AgentClassInterface>>(int)>;

class ManagerTest{
    ManagerTest(const SetUpFunctionTest& setupFunction);
private:
    SetUpFunctionTest m_setUpFunction;
};

the cpp file

ManagerTest::ManagerTest(const SetUpFunctionTest& setupFunction)
        :  m_setUpFunction(setupFunction) {
}

std::shared_ptr<AgentClass> AgentClass::create(){
    auto agentClass = std::shared_ptr<AgentClass>(new AgentClass());
    return agentClass;
}

now in my application.cpp i have code like this

auto setUpFunc = [&](int i) {
    std::shared_ptr<AgentClass> agentInstance = AgentClass::create();

    if(!agentInstance){
        return std::make_pair(false, nullptr);
    }

    return std::make_pair(true,agentInstance);
};

this is returning an error like

/Users/sharmajs/AlexaWorkspace/CA_Manager_POC/projects/avs-cpp-sdk/ApplicationUtilities/DefaultClient/src/DefaultClient.cpp:754:5: error: return type 'pair<[...], typename __unwrap_ref_decay<shared_ptr<AgentClass> &>::type>' must match previous return type 'pair<[...], typename __unwrap_ref_decay<std::nullptr_t>::type>' when lambda expression has unspecified explicit return type
return std::make_pair(true,agentInstance);
^

Reading online it seems like lambda can only have one return statement if i understand correctly and the return type should match so i could technically fix the compilation error by modifying my code like this

    auto setUpFunc = [&](int i) {
    std::shared_ptr<AgentClass> agentInstance = AgentClass::create();

    if(!agentInstance){
        return std::make_pair(false, std::shared_ptr<AgentClass>(nullptr));
    }

    return std::make_pair(true,agentInstance);
};

but that is not desired as now i have to specify AgentClass i want to somehow specify the return type AgentClassInterface in the SetUpFunctionTest so that the application code can even have a return statement like this return std::make_pair(false, nullptr); if needed Please note that i have have other classes also that inherit from AgentClassInterface for full context that the application can provide that other ManagerTest class can use for setup.

Can someone please advise or provide feedback on how i can achieve my desired invocation or any other suggestion/alternatives that could make application code easier to invoke.

Aucun commentaire:

Enregistrer un commentaire