user66875
user66875

Reputation: 2608

c++ optional/default argument

I have defined a method with an optional/defaulted last argument called noAutoResolve as follows:

typedef std::shared_ptr<IMessage> TMessagePtr;

class NetworkService : public IConnectionManagerDelegate, public net::IStreamDelegate
{    
public:   
    void send_message(std::string identity, msg::TMessagePtr msg, QObject* window, std::function<void(int, std::shared_ptr<msg::IMessage> msg)> fn, bool noAutoResolve = false);
}

and later:

void NetworkService::send_message(std::string endpoint, msg::TMessagePtr msg, QObject* window, std::function<void(int res, std::shared_ptr<msg::IMessage> msg)> fn, bool noAutoResolve)
{
}

The linker is now unhappy about unresolved externals in the following line where I intentionally omitted the last argument:

service_->send_message(endpoint_, msg, this, [this](int result, msg::TMessagePtr msg){
        // .....

    });

Is that not possible in c++?

Error LNK1120 1 unresolved externals QTServer QTServer.exe 1
Error LNK2019 unresolved external symbol "public: void __thiscall NetworkService::send_message(class std::basic_string,class std::allocator >,class std::shared_ptr,class QObject *,class std::function)>)" (?send_message@NetworkService@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$shared_ptr@UIMessage@msg@@@3@PAVQObject@@V?$function@$$A6AXHV?$shared_ptr@UIMessage@msg@@@std@@@Z@3@@Z) referenced in function "public: void __thiscall QTWindow::ExecuteCommand(void)" (?ExecuteCommand@QTWindow@@QAEXXZ) QTServer QTWindow.obj 1

Upvotes: 0

Views: 755

Answers (1)

Fatih BAKIR
Fatih BAKIR

Reputation: 4715

The fn parameter of your function is type of std::function<void(int, std::shared_ptr<msg::IMessage> msg)>. However, the lambda you are passing is:

 [this](int result, msg::TMessagePtr msg){
     // .....
 }

This function has the signature of void(int, msg::TMessagePtr), so if there is no conversion from std::shared_ptr<msg::IMessage> to msg::TMessagePtr, the code cannot compile.

Your problem is therefore not about the optional parameter. For a quick fix, if you have access to a C++14 compiler, try getting the lambda parameters as auto:

 [this](auto result, auto msg){
     // .....
 }

Upvotes: 0

Related Questions