I have those functions in some open source lib called uWebSockets
any way I try to run its simple example using Visual Studio 2013.
The function I try to call looks like this:
template <bool isServer>
void Group<isServer>::onMessage(std::function<void (WebSocket<isServer>, char *, size_t, OpCode)> handler) {
messageHandler = handler;
}
and the example looks like this:
int main()
{
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> ws, char *message, size_t length, uWS::OpCode opCode) {
ws.send(message, length, opCode);
});
h.listen(3000);
h.run();
}
The error I'm getting looks like this :
1>D:\dev\cpp\server\uWebSockets\git\uWebSockets\uWebSockets\examples\echo.cpp(9): error C2668: 'uWS::Group<false>::onMessage' : ambiguous call to overloaded function
1> d:\dev\cpp\server\uwebsockets\git\uwebsockets\uwebsockets\src\Group.h(69): could be 'void uWS::Group<false>::onMessage(std::function<void (uWS::WebSocket<false>,char *,size_t,uWS::OpCode)>)'
1> d:\dev\cpp\server\uwebsockets\git\uwebsockets\uwebsockets\src\Group.h(69): or 'void uWS::Group<true>::onMessage(std::function<void (uWS::WebSocket<true>,char *,size_t,uWS::OpCode)>)'
1> while trying to match the argument list '(main::<lambda_f789fc974d6d87c4a2444e6ded66c2a0>)'
Question:
Can I over come the error without upgrading the Visual Studio to 2015?
or it is not related to the compiler version?
UPDATE :
if i set it to : h.onMessage<true> or h.onMessage<uWS::SERVER>
im getting :
This error :
1>D:\dev\cpp\server\uWebSockets\git\uWebSockets\uWebSockets\examples\echo.cpp(10): error C2678: binary '>' : no operator found which takes a left-hand operand of type 'bool' (or there is no acceptable conversion)
1> could be 'built-in C++ operator>(void (__cdecl *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode), void (__cdecl *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode))'
1> or 'built-in C++ operator>(void (__stdcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode), void (__stdcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode))'
1> or 'built-in C++ operator>(void (__fastcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode), void (__fastcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode))'
1> or 'built-in C++ operator>(void (__vectorcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode), void (__vectorcall *)(uWS::WebSocket<true>,char *,size_t,uWS::OpCode))'
1> while trying to match the argument list '(bool, main::<lambda_f789fc974d6d87c4a2444e6ded66c2a0>)'
I got the same errors, after minor fix I got it running:
int main()
{ uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER>* ws, char *message, size_t length, uWS::OpCode opCode) {
ws->send(message, length, opCode);
});
h.listen(3000);
h.run();
}
Related
I have a vector array for classes and im making a method that can delete the classes from that array, using std::remove(). The problem is Weapon (the class) doesn't have an operator == that std::remove needs to compare the elements.
the code:
class Weapon {
public:
std::string name;
Weapon(std::string x) {
name = x;
}
Weapon() {}
};
std::vector<Weapon> inventory{};
void removeInventory(Weapon x) {
if (inventorySize != 0) {
auto deleteFromInc = inventory.erase(std::remove(std::begin(inventory), std::end(inventory), x), std::end(inventory));
if (deleteFromInc != std::end(inventory)) {
std::cout << "Item didn't delete\n";
} else {
if (heldWeapon.name == x.name) {
heldWeapon = Weapon();
}
inventorySize = inventory.size();
std::cout << "Item deleted\n";
}
} else {
std::cout << "You have no items\n";
}
}
the error:
Rebuild started...
1>------ Rebuild All started: Project: rpag, Configuration: Debug Win32 ------
1>rpag.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xmemory(1945,1): error C2678: binary '==': no operator found which takes a left-hand operand of type 'Weapon' (or there is no acceptable conversion)
1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\guiddef.h(192,15): message : could be 'bool operator ==(const GUID &,const GUID &)' [found using argument-dependent lookup]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xmemory(1945,1): message : while trying to match the argument list '(Weapon, const _Ty)'
1> with
1> [
1> _Ty=Weapon
1> ]
1>C:\Users\alber\source\repos\rpag\rpag\rpag.cpp(89): message : see reference to function template instantiation '_FwdIt std::remove<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,Weapon>(_FwdIt,const _FwdIt,const _Ty &)' being compiled
1> with
1> [
1> _FwdIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Weapon>>>,
1> _Ty=Weapon
1> ]
1>Done building project "rpag.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
This is my first question! I hope everything is clear.
std::remove needs operator== (this is requirement of c++ standart library). And you can adds the operator into your class, or use std::remove_if - it use predicate - external function for comparison.
There is third way: you can erase items from vector manually: for (...) { erase ...}
This is a Game Engine for SFML builded in c++. I get some errors that i don't know how to fix it. If someone can solve this problem i will apriciated a lot.
I'm still learning c so por someone could same an obious problem or solucion but i just copied the code from another page and I do exactly the same and mine code isn't working
Errors:
Error C2065: 'StateSystem' : undeclared identifier
Error C2923: 'std::unique_ptr' : 'StateSystem' is not a valid template type
argument for parameter '_Ty'
Error C3203: 'unique_ptr' : unspecialized class template can't be used as a
template argument for template parameter '_Ty', expected a real type
Error C2512: 'std::unique_ptr' : no appropriate default constructor
available
Error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects
3 arguments - 1 provided
1> c:\program files (x86)\microsoft visual studio
12.0\vc\include\xutility(2510) : see declaration of 'std::move'
Error C2893: Failed to specialize function template
'remove_reference<_Ty>::type &&std::move(_Ty &&) throw()'
1> With the following template arguments:
1> '_Ty=Victor::StateRef &'
Error C2227: left of '->Resume' must point to class/struct/union/generic
type
1> type is 'int'
Error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects
3 arguments - 1 provided
1> c:\program files (x86)\microsoft visual studio
12.0\vc\include\xutility(2510) : see declaration of 'std::move'
Error C2893:
Failed to specialize function template 'remove_reference<_Ty>::type
&&std::move(_Ty &&) throw()'
1> With the following template arguments:
1> '_Ty=Victor::StateRef &'
Error C2227: left of '->Initialize' must point to class/struct/union/generic
type
1> type is 'int'
Error C2440: 'return' : cannot convert from 'int' to 'Victor::StateRef &'
And This is the code that provides errors.
State.h
#pragma once
class State
{
public:
virtual void Initialize() = 0;
virtual void HandleInput() = 0;
virtual void Update() = 0;
virtual void Draw(float DeltaTime) = 0;
virtual void Pause()
{
}
virtual void Resume()
{
}
};
StateSystem.h
#pragma once
#include <memory>
#include <stack>
#include "State.h"
typedef std::unique_ptr <StateSystem> StateRef;
class StateSystem
{
public:
StateSystem()
{
}
~StateSystem()
{
}
void AddState(StateRef newStat, bool isReplacing = true);
void RemoveState();
void ProcessStateChanges();
StateRef &GetActiveState();
private:
std::stack<StateRef> _states;
StateRef _newState;
bool _isRemoving;
bool _isAdding;
bool _isReplacing;
};
StateSystem.cpp
#include "StateSystem.h"
void StateSystem::AddState(StateRef newState, bool isRepalcing)
{
this->_isAdding = true;
this->_isReplacing = isRepalcing;
this->_newState = std::move(newState);
}
void StateSystem::RemoveState()
{
this->_isRemoving = true;
}
void StateSystem::ProcessStateChanges()
{
if (this->_isRemoving && !this->_states.empty())
{
this->_states.pop();
if (!this->_states.empty())
{
this->_states.top()->Resume();
}
this->_isRemoving = false;
}
if (this->_isAdding)
{
if (!this->_states.empty())
{
if (this->_isReplacing)
{
this->_states.pop();
}
else
{
this->_states.top()->Pause();
}
}
this->_states.push(std::move(this->_newState));
this->_states.top()->Initialize();
this->_isAdding = false;
}
}
StateRef &StateSystem::GetActiveState()
{
return this->_states.top();
}
there's no StateSystem before typedef std::unique_ptr <StateSystem> StateRef; just add class StateSystem before it.
it says it cannot find the StateSystem class. you have to declare it first like this:
class StateSystem;
typedef std::unique_ptr <StateSystem> StateRef;
class StateSystem
{
//members
};
or put your typedef after the StateSystem definition like this:
class StateSystem
{
//members
};
typedef std::unique_ptr <StateSystem> StateRef;
I'm trying to use a boost::lockfree queue to manage tasks. These tasks retrieve data and would be processed on a worker thread. Once data is retrieved, a signal should be sent to the main thread with the data. The worker thread is spawned at the start of the application and just keeps polling the queue. I'm new to Boost::Asio but from my research, it seems to be the best mechanism for sending signals between threads.
I've looked at several examples, in particular:
Confused when boost::asio::io_service run method blocks/unblocks
boost asio post not working , io_service::run exits right after post
Here is my code:
#include "stdafx.h"
#include <thread>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
#include <boost/signals2.hpp>
typedef boost::signals2::signal<void(int)> signal_type;
class Task
{
public:
Task(int handle) : _handle(handle) {};
~Task() {};
virtual void Execute()
{
int result = _handle * 2;
}
private:
int _handle;
};
class Manager
{
public:
Manager()
{
_mainService = std::make_shared<boost::asio::io_service>();
_workerService = std::make_shared<boost::asio::io_service>();
_work = std::make_shared<boost::asio::io_service::work>(*_workerService);
_threadStarted = false;
Start();
};
~Manager() {};
void WorkerMain()
{
_workerService->poll();
}
void Start()
{
if (_threadStarted) return;
_workerThread = std::thread(&Manager::WorkerMain, this);
_threadStarted = true;
}
void Stop()
{
if (_threadStarted == false) return;
_mainService->stop();
_workerThread.join();
_mainService.reset();
}
void OnSignalFetchCompleted(int value)
{
int asdf = 0; //do stuff with data on main thread
}
void ProcessData(signal_type& signal)
{
int i = 0;
do
{
_queue.consume_one([&](std::shared_ptr<Task> task)
{
task->Execute();
//get data from task; send out signal with data
});
i++;
} while (i < 3);
}
void QueueData(int handle)
{
_signalFetchCompleted.connect(boost::bind(&Manager::OnSignalFetchCompleted, this, _1));
_workerService->post(boost::bind(&Manager::ProcessData, boost::ref(_signalFetchCompleted))); //!!does not compile
std::shared_ptr<Task> task = std::make_shared<Task>(handle);
_queue.push(task);
}
private:
boost::lockfree::spsc_queue<std::shared_ptr<Task>, boost::lockfree::capacity<1024>> _queue;
std::thread _workerThread;
bool _threadStarted;
std::shared_ptr<boost::asio::io_service> _mainService;
std::shared_ptr<boost::asio::io_service> _workerService;
std::shared_ptr<boost::asio::io_service::work> _work;
signal_type _signalFetchCompleted;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::shared_ptr<Manager> mgr = std::make_shared<Manager>();
mgr->QueueData(5);
mgr->QueueData(10);
mgr->Stop();
return 0;
}
I'm getting a compile error on the _workerService->Post line that I haven't been able to resolve:
1>C:\Boost\boost/bind/mem_fn.hpp(333): error C2784: 'T *boost::get_pointer(const boost::scoped_ptr<T> &)' : could not deduce template argument for 'const boost::scoped_ptr<T> &' from 'const signal_type'
1> C:\Boost\boost/smart_ptr/scoped_ptr.hpp(150) : see declaration of 'boost::get_pointer'
1> C:\Boost\boost/bind/mem_fn.hpp(352) : see reference to function template instantiation 'R (__cdecl &boost::_mfi::dm<R,Manager>::call<const U>(U &,const void *) const)' being compiled
1> with
1> [
1> R=void (signal_type &)
1> , U=signal_type
1> ]
1> C:\Boost\boost/bind/mem_fn.hpp(352) : see reference to function template instantiation 'R (__cdecl &boost::_mfi::dm<R,Manager>::call<const U>(U &,const void *) const)' being compiled
1> with
1> [
1> R=void (signal_type &)
1> , U=signal_type
1> ]
1> C:\Boost\boost/bind/bind.hpp(243) : see reference to function template instantiation 'R (__cdecl &boost::_mfi::dm<R,Manager>::operator ()<T>(const U &) const)' being compiled
1> with
1> [
1> R=void (signal_type &)
1> , T=signal_type
1> , U=signal_type
1> ]
Any help resolving this compile error or general comments on this approach would be greatly appreciated. Thanks.
In light of new information, the problem is with your boost::bind. You are trying to call a member function without an object to call it on: you are trying to call ProcessData but you haven't told the bind on which object you wish to call it on. You need to give it a Manager to call it on:
_workerService->post(boost::bind(&Manager::ProcessData, this, boost::ref(_signalFetchCompleted)));
This will call ProcessData on this and pass in a reference to _signalFetchCompleted
The compiler error seems to be talking about you constructing a boost::asio::io_service::work object and that you are passing it incorrect parameters:
error C2664: 'boost::asio::io_service::work::work(const boost::asio::io_service::work &)' : cannot convert argument 1 from 'std::shared_ptr<boost::asio::io_service>' to 'boost::asio::io_service &'
boost::asio::io_service::work has a constructor which takes a boost::asio::io_service& and a copy constructor; however, you are passing it a std::shared_ptr<boost::asio::io_service>:
_work = std::make_shared<boost::asio::io_service::work>(_workerService);
Here, _workerService is a std::shared_ptr<boost::asio::io_service>, but you need a boost::asio::io_service&. Try the following instead:
_work = std::make_shared<boost::asio::io_service::work>(*_workerService);
I think that boost::asio is not the best solution for your task. Have you read about conditional variables? They are much more simple and can be used to achieve your goal.
I wrote an unit test with hippomocks, but got error while compiling it.
The compiler is VS 2010.
How can I fix it ?
#include "hippomocks.h"
#include <functional>
using namespace HippoMocks;
struct A
{
virtual void f(std::function<void (int)> arg);
};
int main(void)
{
MockRepository mock;
A* aptr = mock.Mock<A>();
mock.ExpectCall(aptr, A::f); // error
return 0;
}
The output is :
main.cpp
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : wa
rning C4530: C++ exception handler used, but unwind semantics are not enabled. S
pecify /EHsc
c:\users\cong\project\test\test\hippomocks.h(466) : error C2593: 'operator <<' i
s ambiguous
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\ostream(2
06): could be 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Trai
ts>::operator <<(std::_Bool)'
with
[
_Elem=char,
_Traits=std::char_traits<char>
]
c:\users\cong\project\test\test\hippomocks.h(441): or 'std::ostrea
m &HippoMocks::operator <<(std::ostream &,const HippoMocks::NotPrintable &)'
while trying to match the argument list '(std::ostream, std::tr1::functi
on<_Fty>)'
with
[
_Fty=void (int)
]
c:\users\cong\project\test\test\hippomocks.h(463) : while compiling clas
s template member function 'void HippoMocks::printArg<T>::print(std::ostream &,T
,bool)'
with
[
T=std::tr1::function<void (int)>
]
c:\users\cong\project\test\test\hippomocks.h(614) : see reference to cla
ss template instantiation 'HippoMocks::printArg<T>' being compiled
with
[
T=std::tr1::function<void (int)>
]
Enhancing #dascandy's comment here is how his method can look like. Place it after including hippomocks.h:
template<>
struct printArg<std::function<void (int)> >
{
static inline void print(std::ostream &os, std::function<void (int)> arg, bool withComma)
{
if (withComma)
{
os << ",";
}
if (arg)
{
os << "true";
}
else
{
os << "false";
}
}
};
Note that I didn't test this very example but rather took our solution and adapted the type to the original post's example. I'd be happy to know whether this works for you.
I just have a very basic class that gives with functions that return the winning team of a match.
here's team.cpp
class teams
{
string teamName;
string teamName2;
int score;
int score2;
public:
teams ();
void set_team1();
void set_team2();
string get_score()
{
if (score > score2)
{
return teamName;
}
else
{
return teamName2;
}
}
private:
void teams::set_team1(string teamName, int score)
{
this->teamName=teamName;
this->score=score;
}
void teams::set_team2(string teamName2, int score2)
{
this->teamName2=teamName2;
this->score2=score2;
}
};
and here's is the line where i'm getting the error in the main method. I'm trying to create a teams object.
firstTeam.set_team1(teamName, score);
firstTeam.set_team2(teamName2, score2);
Visual studio comes up and says "error: no instance of overloaded function "team::set_team1" matches the argument list".
What am I missing?
This is the exact error I get:
1>c:\users\lab8.cpp(31): error C2664: 'void teams::set_team1(std::string,int)' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::string'
1> with
1> [
1> _Ty=std::string
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>c:\users\lab8.cpp(32): error C2664: 'void teams::set_team2(std::string,int)' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::string'
1> with
1> [
1> _Ty=std::string
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> Generating Code...
1>
1>Build FAILED.
error C2664: 'void teams::set_team1(std::string,int)' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::string'
From the error message, it is clear that first parameter isn't of type std::string. It is actually a std::vector. So,
firstTeam.set_team1(teamName, score); // Check what is the type of teamName
If you can see that teamName is actually a std::string, then check whether you are compiling the right file. Save the file and try again because the code you posted and the error message has no relation.
Compiler don't provide default constructor( constructor with no arguments ) in case your class overloads the constructor.
class teams
{
string teamName;
string teamName2;
int score;
int score2;
// ...
public:
teams( string t, int s ) : teamName(x), score(s)
// Initializer list
{}
};
But the I don't understand, why you have teamName2, score2 members as members of teams. What if there are 10 teams? Just have an instance for each team and compare them with other instances of teams.
You have declared the two methods without parameters. Convert:
void set_team1();
void set_team2();
into:
void set_team1(string, int);
void set_team2(string, int);