c++ optional/default argument - c++

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

Related

unresolved external symbol "__declspec(dllimport)"

I'm trying to code a little plugin for bakkesmod because I'm pissing myself off.
I watched the only 2 video that exists on this topic but ... it doesn't work and I have this error for each void - >> Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: void __thiscall GameWrapper::HookEvent(class std::basic_string<char,struct std::char_traits,class std::allocator >,class std::function<void __cdecl(class std::basic_string<char,struct std::char_traits,class std::allocator >)>)" (_imp?HookEvent#GameWrapper##QAEXV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##V?$function#$$A6AXV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std###Z#3##Z) TagName C:\Users\leodu\source\repos\TagName\TagName\TrollTagName.obj 1
here is my code.
TroolTagName.cpp (not judge the name)
#include "TrollTagName.h"
BAKKESMOD_PLUGIN(TroolTagName, "Trool Tag Name", "1.0", PERMISSION_ALL)
void TroolTagName::onLoad()
{
this->Log("This is my first Bakkesmod Plugin");
this->LoadHooks();
}
void TroolTagName::onUnload()
{
}
void TroolTagName::LoadHooks()
{
gameWrapper->HookEvent("Function TAGame.GameEvent_Soccar_TA.EventMatchEnded", std::bind(&TroolTagName::GameEndedEvent, this, std::placeholders::_1));
gameWrapper->HookEvent("Function TAGame.AchievementManager_TA.HandleMatchEnded", std::bind(&TroolTagName::GameEndedEvent, this, std::placeholders::_1));
}
void TroolTagName::GameEndedEvent(std::string name)
{
cvarManager->executeCommand("load_freeplay");
}
void TroolTagName::Log(std::string msg)
{
cvarManager->log("TroolTagName: " + msg);
}
TroolTagName.h
#include "bakkesmod\plugin\bakkesmodplugin.h"
#pragma comment(lib, "pluginsdk.lib")
class TroolTagName : public BakkesMod::Plugin::BakkesModPlugin
{
public:
virtual void onLoad();
virtual void onUnload();
void LoadHooks();
void GameEndedEvent(std::string name);
private:
void Log(std::string msg);
};
The project and a Dynamic-library dll project.
I tried adding __declspec (dllexport) before void but ... I got this error - >> redefinition; different linkage and I found nothing for this error so I am blocked :(

ThreadPool class: can't pass the args straight

I have a Thread pool of the type that can be found here.
I try doing the following:
/* Allocate a ThreadPool */
shared_ptr<SpinTools::ThreadPool> pool(new SpinTools::ThreadPool(4));
/* Start processing each image in Core container */
for (int img_idx = 0; img_idx < num_images; img_idx++) {
pool->enqueue(_worker_task, img_idx, _args, _stats);
}
My worker task has the following prototype:
void _worker_task(int img_idx, ProcessorArgs &args, Stats &stats)
however this won't compile and MSVC displays the error
Error 14 error LNK2019: unresolved external symbol "public: class std::future<void> __cdecl ThreadPool::enqueue<void (__cdecl&)(int,struct ProcessorArgs,struct SpinCore::Features::Stats &),int &,struct Sift::ProcessorArgs &,struct SpinCore::Features::Stats &>(void (__cdecl&)(int,struct ProcessorArgs,struct SpinCore::Features::Stats &),int &,struct ProcessorArgs &,struct SpinCore::Features::Stats &)" (??$enqueue#A6AXHUProcessorArgs#Sift##AEAUStats#Features#SpinCore###ZAEAHAEAU12#AEAU345##ThreadPool#SpinTools##QEAA?AV?$future#X#std##A6AXHUProcessorArgs#Sift##AEAUStats#Features#SpinCore###ZAEAHAEAU45#1#Z) referenced in function "public: virtual void __cdecl Sift::process(void)" (?process#Sift##UEAAXXZ)
Edit: adding the header for ThreadPool::enqueue for completness:
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
You need to place the implementation of ThreadPool::enqueue in the header. MSVC can't generate the implementation if it's in .cpp file only (or at least earlier versions could not)

C++ Template/Generics error

I have a simple function setup to check if a value is in a std::vector, and I would like to use a 'Template' to beable to use the function with all classes.
Some definitions
std::vector<ItemID_t> *spareItems;
ItemID_t newItem;//note this is an enumeration value
The function works perfectly if I call with
bool b = !vectorContains(*spareItems,newItem);
and the function looks like
bool vectorContains(std::vector<ItemID_t> &vector,const ItemID_t& value){
return std::find(vector.begin(), vector.end(), value)!=vector.end();
}
but if I try to implement generics with the call
bool b = !vectorContains<ItemID_t>(*spareItems,newItem);
and the function definition
template <class T>
bool vectorContains(std::vector<T> &vector,const T& value){
return std::find(vector.begin(), vector.end(), value)!=vector.end();
}
It fails in the second example and gives me this linker error
error LNK2019: unresolved external symbol "bool __cdecl turtle::vectorContains<enum turtle::ItemID_t>(class std::vector<enum turtle::ItemID_t,class std::allocator<enum turtle::ItemID_t> > &,enum turtle::ItemID_t const &)" (??$vectorContains#W4ItemID_t#turtle###turtle##YA_NAAV?$vector#W4ItemID_t#turtle##V?$allocator#W4ItemID_t#turtle###std###std##ABW4ItemID_t#0##Z) referenced in function "public: void __thiscall turtle::Barracks::swapItems(int,enum turtle::ItemID_t)" (?swapItems#Barracks#turtle##QAEXHW4ItemID_t#2##Z)
Thank you

Templated class linking error when used to declare object in other class

I created a templated data class (CAnyData, please see its header file copy for your reference), with which I declared some variables in my another class (CConstantDataBlock, please see its header file copy for your reference). As you may see, the latter one is nearly an empty class. But when I compiled my project, the VS2008 compiler thowed the following linking errors. Would please help me figure out what's wrong with my CConstantDataBlock and/or CAnyData?
1>------ Build started: Project: Tips, Configuration: Debug Win32 ------
1>Compiling...
1>ConstantDataBlock.cpp
1>Linking...
1> Creating library F:\Tips\Debug\Tips.lib and object F:\Tips\Debug\Tips.exp
1>ConstantDataBlock.obj : error LNK2019: unresolved external symbol "public: __thiscall CAnyData<double>::~CAnyData<double>(void)" (??1?$CAnyData#N##QAE#XZ) referenced in function __unwindfunclet$??0CConstantDataBlock##QAE#XZ$0
1>ConstantDataBlock.obj : error LNK2019: unresolved external symbol "public: __thiscall CAnyData<int>::~CAnyData<int>(void)" (??1?$CAnyData#H##QAE#XZ) referenced in function __unwindfunclet$??0CConstantDataBlock##QAE#XZ$0
1>ConstantDataBlock.obj : error LNK2019: unresolved external symbol "public: __thiscall CAnyData<double>::CAnyData<double>(void)" (??0?$CAnyData#N##QAE#XZ) referenced in function "public: __thiscall CConstantDataBlock::CConstantDataBlock(void)" (??0CConstantDataBlock##QAE#XZ)
1>ConstantDataBlock.obj : error LNK2019: unresolved external symbol "public: __thiscall CAnyData<int>::CAnyData<int>(void)" (??0?$CAnyData#H##QAE#XZ) referenced in function "public: __thiscall CConstantDataBlock::CConstantDataBlock(void)" (??0CConstantDataBlock##QAE#XZ)
1>F:\Tips\Debug\Tips.exe : fatal error LNK1120: 4 unresolved externals
1>Build log was saved at "file://f:\Tips\Tips\Debug\BuildLog.htm"
1>Tips - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
#pragma once
#include <string>
using namespace std;
template <class T>
class CAnyData
{
public:
CAnyData(void);
CAnyData(int nWordNumber, string sContents, T Type, int nWidth, int nPrecision);
~CAnyData(void);
// Operators
CAnyData( const CAnyData& rhs );
const CAnyData& operator = (const CAnyData& rhs);
// Must define less than relative to name objects.
bool operator<( const CAnyData& AnyData ) const;
// Compares profile's of two objects which represent CAnyData
inline bool operator ==(const CAnyData& rhs) const;
// Get properties
inline int WordNumber() const { return m_nWordNumber; }
inline const string& Contents() const { return m_sContents; }
inline const T& DataType() const { return m_Type; }
inline int Width() const { return m_nWidth; }
inline int Precision() const { return m_nPrecision; }
// Set properties
void WordNumber(int nWordNumber) const { m_nWordNumber = nWordNumber; }
void Contents(string sContents) const { m_sContents = sContents; }
void DataType(T Type) const { m_Type = Type; }
void Width(int nWidth) const { m_nWidth = nWidth; }
void Precision(int nPrecision) const { m_nPrecision = nPrecision; }
protected:
void Init(void);
protected:
int m_nWordNumber;
string m_sContents;
T m_Type;
int m_nWidth;
int m_nPrecision;
};
#pragma once
#include "AnyData.h"
// Constants block
// This block consists of 64 words to be filled with useful constants.
class CConstantDataBlock
{
public:
CConstantDataBlock(void);
~CConstantDataBlock(void);
protected:
CAnyData<int> m_nEarthEquatorialRadius;
CAnyData<int> m_nNominalSatelliteHeight;
CAnyData<double> m_dEarthCircumference;
CAnyData<double> m_dEarthInverseFlattening;
};
It seems that you do not have definitions for several of the methods of CAnyData, including the default constructor and the destructor. When you use these in your CConstantDataBlock-class, the constructor and destructor are required though.
Since CAnyData is a class-template, all definitions should be written directly into the header-file (just as you have done with all the getters and setters).

C++ LNK2019 ( between project classes )

I have an very strange error: when I want to use the SocialServer::Client class from my SocialServer::Server class, the linker threw me two LNK2019 errors :
Error 1 error LNK2019: unresolved external symbol "public: void __thiscall SocialServer::Client::Handle(void)" (?Handle#Client#SocialServer##QAEXXZ) referenced in function "private: static unsigned int __stdcall SocialServer::Server::listenThread(void *)" (?listenThread#Server#SocialServer##CGIPAX#Z) C:\Users\benjamin\Documents\Visual Studio 2010\Projects\FCX Social Server\SocialServer Core\Server.obj SocialServer Core
Error 2 error LNK2019: unresolved external symbol "public: __thiscall SocialServer::Client::Client(unsigned int)" (??0Client#SocialServer##QAE#I#Z) referenced in function "private: static unsigned int __stdcall SocialServer::Server::listenThread(void *)" (?listenThread#Server#SocialServer##CGIPAX#Z) C:\Users\benjamin\Documents\Visual Studio 2010\Projects\FCX Social Server\SocialServer Core\Server.obj SocialServer Core
However , these 2 missing function are correctly implemented :
Client.h
#pragma once
#include "dll.h"
namespace SocialServer
{
class __social_class Client
{
public:
Client(SOCKET sock);
~Client();
void Handle();
private:
static unsigned __stdcall clientThread(void* value);
SOCKET _socket;
uintptr_t _thread;
unsigned int _thread_id;
};
}
Client.cpp
#pragma once
#include "Client.h"
namespace SocialServer
{
Client::Client(SOCKET socket)
{
this->_socket = socket;
}
Client::~Client()
{
}
void Client::Handle()
{
std::cout << " New client " << std::endl;
this->_thread = _beginthreadex(NULL, 0, Client::clientThread, &this->_socket, CREATE_SUSPENDED, &this->_thread_id);
ResumeThread((HANDLE)this->_thread);
}
unsigned __stdcall Client::clientThread(void* value)
{
// Some code to execute here ...
}
}
Where does the problem comes from ?
i've found the solution.
In a function that's used by _beginthreadex() (with unsigned __stdcall) , always add a return at the end.