简体   繁体   中英

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

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){
     // .....
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM