std::thread initialization constructor gives compile error - c++

i'm working into a Visual Studio project (v120 Compiler) that uses std::thread to read from usb device aside from the GUI, and the function throws an error : "Error C2661 'std::thread::thread' : no overloaded function takes 3 arguments"
here's code:
class IOThread
{
public:
IOThread(DeviceHandler *handle) : _handle(handle)
~IOThread();
std::thread *getThread(ThreadType type);
template <typename T>
void execRead(std::list<T> *dataStack)
{
std::thread *thread = getThread(Read);
if (thread == NULL)
{
thread = new std::thread(&DeviceHandler::readFromBus, _handle, dataStack);
_threadPool.push_back(std::make_pair(Read, thread));
}
}
private:
DeviceHandler *_handle;
std::vector<std::pair<ThreadType, std::thread *>> _threadPool;
};
moreover, DeviceHandler is an abstraction class, which defines pure virtual readFromBus function, which prototype is the following
template <typename T>
void readFromBus(std::list<T> *dataStack) = 0;
I wish you not to have the same headache as i do while solving this mess...
Regards,

As explained in the comments your situation is the same is in this question. Because the method DeviceHandler::readFromBus() is templated arbitrarily many overloads can be generated. (They share the name but have different signatures).
Because of this the compiler cannot select the correct overload, hence the error message. You will need to tell the compiler which overload to use by a cast. (as this answer explains)
The following cast should do:
thread = new std::thread(
static_cast<void (DeviceHandler::*)(std::list<T> *)>(&DeviceHandler::readFromBus),
_handle, dataStack);

I tried to give a MVCE of the error, but i can't test if it compiles;
but here's the actual structure of classes using your cast
thread = new std::thread(
static_cast<void (DeviceHandler::*)(std::list<T> *)>(&DeviceHandler::readFromBus),
_handle, dataStack);
http://ideone.com/gVh1Du
EDIT: I solved the problem, the issue was the templated pure definition, which i replaced by a function that takes in parameters an abstract struct as follows
typedef struct s_dataStack
{
DataType type;
std::list<void *> stack;
} t_dataStack;
and then i cast any stack element with provided type in enum "datatype".
Thanks for the help given anyway, it led me to the origins of the issue.

Related

Strange error from CBuilder at compile time using dynamic_cast for similar types

Using C++ Builder 5.0
template <class HYPERSPACE>
inline
bool IsAtLeastHYPERSPACE(hyperspace_t **_)
{ return (dynamic_cast<HYPERSPACE **>(_) != 0); }
that produces a compile error E2031 : cannot cast from 'hyperspace_t **' to 'hyperspace_t **'...
So should I assume that C++ cannot cast from a class to the SAME class pointer ?
Then, how to check if the class of an object's pointer is an overloaded class ?
Really blocked by that strange error....
Help appreciated... So I could at least compile...
Oups... I found my mistake :
As the parameter is an array of pointers of a parent class, I cannot cast it to an array of pointers to a derived class, but only cast to a derived class, a specific element of that source array...
So the code became...
template <class HYPERSPACE>
inline
bool IsAtLeastHYPERSPACE(hyperspace_t **_)
{ return (dynamic_cast<HYPERSPACE *>(_[0]) != 0); }
Notice _[0] instead of _ and HYPERSPACE * instead of HYPERSPACE **
That's all folks...

Function/Method pointers Pushed to a Deque

I am making a Queue for running functions. I put the functions that require being called into a std::deque<bool(*)()> Then I later on cycle through the deque calling each function and letting it run, sometimes even doing things based on the return.
The problem I am having is actually with regards to placing these functions inside of the deque.
I have this deque inside a class called A2_Game. I also have a class called Button.
My code resembles the following:
class Button
{
bool DoInput();
}
class A2_Game
{
std::deque<bool(*)()> Input_Functions;
bool EnterName()
}
A2_Game::OtherMethod()
{
Button* btn1 = new Button();
Input_Functions.push_back(&A2_Game::EnterName); //The compiler told me to do this and it still won't compile the line..
Input_Functions.push_back(btn1->DoInput);
//Loop
}
I cannot determine how to fix my compile errors. I suspect some of you may be able to just tell me outright what needs to be changed/done in order to get this to compile, by looking at what I've shown here. In case that is !true then here are the compile errors.
error C2664: 'std::deque<_Ty>::push_back' : cannot convert parameter 1 from 'bool (__thiscall A2_Game::* )(void)' to 'bool (__cdecl *const &)(void)'
error C3867: 'Button::Doinput': function call missing argument list; use '&Button::Doinput' to create a pointer to member
if you want to push back functions you can use std::function (or boost if your compiler doesn't support c++11)
std::deque<std::function<bool()> > function_list;
Button* btn1 = new Button();
function_list.push_back([this](){return EnterName();});
function_list.push_back([btn1](){return btn1->DoInput();});
make sure everything in the lambda is still going to be valid when you call it from the function_list.
EDIT:
boost equivalent
std::deque<boost::function<bool()> > function_list;
Button* btn1 = new Button();
function_list.push_back(boost::bind(&A2_Game::EnterName,this));
function_list.push_back(boost::bind(&Button::DoInput,btn1));
The problem is that the signature of the class methods don't match with the function signature bool (*)(). The signatures of the two methods are bool (Button::*)(); or bool (A2_Game::*)(); respectively. (The actual class to which the method belongs is part of its signature!)
The solution here is to use functors/function objects. Functors are wrapper objects around "callable elements" that are useful if you want to treat functions like objects (in a OOP sense). If you have boost at hand your code could look similar to this (code compiles):
#include <boost/function.hpp>
#include <deque>
class Button
{
public:
bool DoInput() { return true; }
};
class A2_Game
{
public:
typedef boost::function<bool()> Functor;
std::deque<Functor> Input_Functions;
bool EnterName() { return true; }
void OtherMethod();
};
void A2_Game::OtherMethod()
{
Button* btn1 = new Button();
Input_Functions.push_back(boost::bind(&A2_Game::EnterName, this));
Input_Functions.push_back(boost::bind(&Button::DoInput, btn1));
}
boost::bind combines a function pointer with the reference to an actual class instance and returns an function object of the same type as A2_Game::Functor.
Note that boost::function has been integrated into the C++11 standard (see here), so if your project supports C++11 simply use #include <functional> and std instead of boost namespaces.

cannot convert between nested templated types

I am trying to write a message handler whose Base classes are
1-Handler base class
2-Handler Factory that generates proper handler for a proper message type
3-and a base generic class for message
their code is like this:
#include <map>
#include<iostream>
//Base Handler
template<class MSG>
class Handler
{
MSG message;
public:
Handler(MSG message):message(message){
}
virtual void handle() = 0;
MSG getMessage()
{
return message;
}
};
//Base Handler Factory
template<class MSG>
class HandlerFactory {
public:
virtual Handler<MSG> * create(MSG & message) = 0;
};
//Base message
template<class T>
class Message
{
T messageType;
public:
T getMessageType()
{
return messageType;
}
void setMessageType(T messageType_)
{
messageType = messageType_;
}
};
//Then, based on the message type, I write subclass for every base class:
//my custom types
enum MessageType
{
ANNOUNCE,
KEY_SEND,
KEY_REQUEST
};
//my first custom message format
class MyMessage_1 : public Message<MessageType>
{
//...
};
//my first custom handler
class MyMessageHandler_1 : public Handler<MyMessage_1>
{
public:
MyMessageHandler_1(MyMessage_1 &message_): Handler<MyMessage_1>(message_)
{
}
void handle(){}
};
//my custom handler factory
class MyHandlerFactory : public HandlerFactory<Message<MessageType> > {
Handler<Message<MessageType> > *value;
public:
MyHandlerFactory(){};
Handler<Message<MessageType> > * create(Message<MessageType> & message){
switch (message.getMessageType())
{
case ANNOUNCE:
MyMessage_1 t1;
value = new MyMessageHandler_1(t1);//error here
break;
//etc. etc.
default:
value = 0;
break;
};
return value;
};
};
//let's put a main so you can easily compile it
int main()
{
}
the problem is when, in switch-case clause, I try to create an instance of a handler for one of my custom message classes, I get the following error:
templateArgList.cpp: In member function ‘virtual Handler<Message<MessageType> >* MyHandlerFactory::create(Message<MessageType>&)’:
templateArgList.cpp:86:37: error: cannot convert ‘MyMessageHandler_1*’ to ‘Handler<Message<MessageType> >*’ in assignment
I was under the impression that:
Handler<Message<MessageType> > * can be casted as follows:
MyMessageHandler_1-> Handler<MyMessage_1>
^
|
`Message<MessageType>` which finally gives me:
`Handler<Message<MessageType> >` :P
Am I wrong? of course I am, why would I get the above error then :))
I just don't know why and how to fix it.
Therefore I will appreciate if you kindly help me with it.
thanks very much for your kind help
Here is a very simple program that is analogous to what you have done, but without the nested templates so that it's understandable:
#include <vector>
class A {
};
class B : public A {
};
int main() {
std::vector<A>* va;
va = new std::vector<B>;
}
And indeed, g++ gives the error:
error: cannot convert ‘std::vector<B>*’ to ‘std::vector<A>*’ in assignment
This should be clear -- a vector of A's is not the same as a vector of B's, even though B inherits from A. To be able to take advantage of inheritance, you have to have pointers to the objects that are related. For example:
int main() {
std::vector<A*> va(3);
for (int i=0; i<3; ++i) {
va[i] = new B;
}
}
The analogy here is:
std::vector< > ----> Handler< >
A ----> Message<MessageType>
B ----> MyMessage_1
By the way, did you realize that you define a variable named message in both MyMessageHandler_1 and also in Handler<>? This will cause MyMessageHandler_1::message to hide Handler<>::message. I'm not sure if this is what you want.
Also.. you might want to look into the Twisted package for Python, as it might be well suited to the application you're building. (If you don't mind using Python.)
Question: "any suggestion to alter my code?"
Response:
Well, I would try removing the templates and enjoying the power of inheritance. The Handler class can accept a Message object (or reference or pointer), as both of these are base classes. The HandlerFactory's create would also accept a Message object. Then you can proceed with the Message class having an enum MessageType type member variable and using switch inside HandlerFactor to determine the correct Handler-derived class to create.
Or instead of the enum, you could exploit inheritance even further by adding a "NewHandler()" function to Message, which would be pure virtual in Message and would be defined in the derived class. This way, you wouldn't need a switch -- each type of message knows what Handler it needs, and the factor simply calls message->NewHandler().
...It's a bit difficult to determine whether you need to use templates or not because I'm not sure where your project is headed. However, as a rough rule of thumb, it's a good idea to use templates when (a) you want to use equivalent blocks of code for different types and (b) you can't use inheritance to accomplish it. The std::vector<> is a good example -- the behavior of std::vector<int> and std::vector<float> is the same, but int's and float's aren't related by any common base, so rather than rewrite the code for a VectorI and VectorF, the compiler is asked to rewrite the code instead.
So far, it looks like you can exploit inheritance to do what you want. It has the added bonus of making it easier for other people to read your code, as well. :)

C++ polymorphism with template interface

Timer.h:
template<class T>
class Timer {
public:
typedef T Units;
virtual Units get() = 0;
};
TimerImpl.h:
class TimerImpl: public Timer<long> {
public:
TimerImpl() {
}
~TimerImpl() {
}
long get();
};
FpsMeter.h(version 1):
template <class T>
class FpsMeter {
private:
Timer<T>* timer;
public:
FpsMeter (Timer<T>* timer) {
this->timer = timer;
}
...
};
This example works. But it does not look pretty.
Timer<long>* t = new TimerImpl();
FpsMeter<long>* f1 = new FpsMeter<long> (t);
Here there are a lot of extra template uses. How can I realize this idea of multy-type interface when the type is defined by the implementation and user class has not to define new type, it should use the type of the implementation.
If you don't mind a helper template function which always creates FpsMeter on the heap you could something like the following
template < class T >
FpsMeter<T> *make_FpsMeter( Timer<T> *timer ) {
return new FpsMeter<T>( timer );
}
Then creating a FpsMeter of the appropriate type is like so
FpsMeter<long> *f1 = make_FpsMeter( new TimerImpl() );
Or if you can use C++11 auto you'd get
auto f1 = make_FpsMeter( new TimerImpl() );
This is the best you can do in C++, as far as I know. FpsCounter needs to know the type T so that it knows which Timer<T> implementations it can accept. Your sample code can be made somewhat simpler:
FpsMeter<long>* f1 = new FpsMeter<long> (new TimerImpl());
...which at least gets you out of repeating the template type, but of course in that case FpsMeter must take responsibility for deleting the TimerImpl, ideally through an auto_ptr or such.
I'd question, too, whether you really need to vary the return value of get(). What sorts of values do you expect it to return, besides long?
Maybe you can take inspiration from the <chrono> library from C++11 (also available in boost). Or better yet, save yourself some time and just use it directly. It's efficient, safe, flexible, and easy to use.
If you want to use only timers based on implementation of machine timer (which should be defined at compilation stage for entire program I assume), i would simply use typedef and perhaps some preprocessor magic to get it right:
[...]
#if TIMER_LONG // Here you should somehow check what type is used on target platform.
typedef Timer<long> implTimer;
typedef FpsMeter<long> implFpsMeter;
#else // If eg. using double?
typedef Timer<double> implTimer;
typedef FpsMeter<double> implFpsMeter;
#fi
This should make user code unaware of actual typee used, as long it is using implTimer and implFpsMeter.
If you mean that some parts of code will use different TimerImpl then you should make your FpsMeter class polymorphic
class FpsMeter{
public:
virtual double fps()=0;
virutal void newFrame()=0;
[...]
//Class counts new frames and using internal timer calculates fps.
};
template <typename T>
class FpsMeterImpl: public FpsMeter{
TimerImpl<T>* timer;
public:
FpsMeterImpl(TimerImpl<T>* timer);
virtual double fps();
virutal void newFrame();
};

Pass any member function of any class as a Callback function

I'm working on a OpenGL menu which contains some buttons. I want to be able to associate an action (member function (with a fixed signature) of any class!) to a button which gets executed when the button is pressed. I can do it right now but only for one type. I want to be able to use any member function of any class for my callback.
Right now I'm doing it like this:
#define BUTTONCALLBACK(Func) bind1st( mem_fun( &ClassICanSupport::Func ), this )
I can then create a button like this:
Button* b = new Button("Bla", BUTTONCALLBACK(functionIWanttoCall));
The Callback function has the following signature:
void callback(Button* source);
When I press the button I can execute the callback function which I passed.
I had a look at boost::bind but I couldn't really find a way to tackle the problem. Furthermore all my classes are derived from a class Object so I thought about a void* which I could convert to the right class with some typeid hack but I was unable to get it working. At the end I always had the problem that I couldn't completly eliminate the class type of the callback function (which would be necessary to save the function pointer in my button class) and still being able to call the function.
Do you have any idea how to tackle this problem?
Don't use pointers, use boost::function together with boost::bind (or std::function and std::bind if C++0x), something like
// in Button class (or whatever signature you need)
Button(const std::string&, boost::function<void(Button*)> callback) // ...
// you can then use callback as a function
// in calling code
Button *b = new Button("..", boost::bind(&Class::func, this));
You should use a function<void(Button*)> object. These are run-time polymorphic and can be used with any object that supports void operator()(Button*). You can find one in Boost, TR1 and C++0x. boost::bind works well with these objects.
Well, the easiest way would be with virtual functions, if you don't want to pull in Boost or don't have access to C++0x.
#include <iostream>
// fwd declare
class Button;
class BtnCallbackBase{
public:
virtual void operator()(Button*) = 0;
};
template<class C>
class BtnCallback : public BtnCallbackBase{
private:
typedef void (C::*callback_func)(Button*);
C* _object;
callback_func _onclick;
public:
BtnCallback(C* obj, callback_func func)
: _object(obj)
, _onclick(func)
{}
virtual void operator()(Button* btn){
(_object->*_onclick)(btn);
}
};
class Button{
public:
Button()
: _onclick(0)
{}
void Click(){
if(_onclick != 0)
(*_onclick)(this);
}
template<class C>
void RegisterCallback(C* obj, void (C::*func)(Button*)){
// cleanup old callback, deleting null pointer is a noop
delete _onclick;
_onclick = new BtnCallback<C>(obj,func);
}
~Button(){
delete _onclick;
}
private:
BtnCallbackBase* _onclick;
};
class MyClass{
public:
void ExampleCallback(Button* btn){
std::cout << "Callback works!\n";
}
};
int main(){
Button btn;
MyClass test;
btn.RegisterCallback(&test, &MyClass::ExampleCallback);
btn.Click();
}
Full example on Ideone.
If you want a solution to your problem without using Boost library / without using new C++ features then one of the best choice is Generic Callbacks Dispatcher discussed by Danny Kalev / Herb Sutter.
http://www.gotw.ca/gotw/083.htm