I have the class DvQkdLdpcTxMessageProcessorReceiver as follow:
#ifndef DV_QKD_LDPC_TX_MESSAGE_PROCESSOR_RECEIVER_H_
#define DV_QKD_LDPC_TX_MESSAGE_PROCESSOR_RECEIVER_H_
#include "netxpto_20200819.h"
#include "dv_qkd_message_processor_common_20200819.h"
class DvQkdLdpcTxMessageProcessorReceiver : public Block
{
public:
DvQkdLdpcTxMessageProcessorReceiver(std::initializer_list<Signal*> InputSig, std::initializer_list<Signal*> OutputSig) : Block(InputSig, OutputSig) {};
void initialize(void);
bool runBlock(void);
private:
// Input Parameters ##################################################################################
// State Variables ###################################################################################
std::vector<t_message> storedMessages{};
// Basis Reconciliation
t_integer messageReconciliationMaximumDataLength{ 4096 };
CircularBuffer<t_binary> BasesFrom{ messageReconciliationMaximumDataLength };
// Parameter Estimation
t_integer messageParameterEstimationMaximumDataLength{ 100 };
t_integer numberOfProcessedBits{ -1 };
CircularBuffer<t_integer> SeedFrom{ 10 };
CircularBuffer<t_integer> RatioFrom{ 10 };
CircularBuffer<t_integer> NumberOfBitsPerEstimationBlockFrom{ 10 };
CircularBuffer<t_binary> DataFrom{ 10*(size_t) messageParameterEstimationMaximumDataLength };
// Error correction - Parities
std::vector<t_integer> parityIn{};
bool errCorrParitiesStarted{ false };
// Sindrome
t_integer messageSindromeMaximumDataLength{ 5000 };
CircularBuffer<t_binary> Sindrome{ messageSindromeMaximumDataLength };
// Error correction - Permutations
std::vector<t_integer> permutationsIn{};
bool errCorrPermStarted{ false };
// Error correction - BER
std::vector<t_integer> errCorrBerIn{};
bool errCorrBerStarted{ false };
// Privacy amplification seeds
std::vector<t_integer> privacySeedsIn{};
bool privacySeedsStarted{ false };
bool outputReceivedData(std::vector <t_integer>& dataVector, Signal& outputSignal, bool &started);
};
#endif // !MESSAGE_PROCESSOR_RECEIVER_H_
The parent class is defined as:
class Block {
public:
/* Methods */
Block(){};
Block(std::vector<Signal*> &InputSig, std::vector<Signal*> &OutputSig);
Block(std::initializer_list<Signal*> InputSig, std::initializer_list<Signal*> OutputSig); // since C++11
//void initializeBlock(std::vector<Signal*> InputSig, vector<Signal*> OutputSig);
void initializeBlock();
virtual void initialize(void) {};
//bool runBlock();
virtual bool runBlock();
void terminateBlock();
virtual void terminate(void) {};
void closeOutputSignals();
void setNumberOfInputSignals(int nOfInputSignal) { numberOfInputSignals = nOfInputSignal; };
int getNumberOfInputSignals() { return numberOfInputSignals; };
void setNumberOfOutputSignals(int nOfOutputSignal) { numberOfOutputSignals = nOfOutputSignal; };
int getNumberOfOutputSignals() { return numberOfOutputSignals; };
void setLogValue(bool lValue) { logValue = lValue; }
bool getLogValue() { return logValue; }
void setFirstRun(bool fRun) { firstRun = fRun; }
bool getFirstRun() { return firstRun; }
void setFirstTime(bool fTime) { firstTime = fTime; }
bool getFirstTime() { return firstTime; }
void setTerminated(bool t) { terminated = t; }
bool getTerminated() { return terminated; }
std::string getSignalsFolderName();
void setVerboseMode(t_bool vMode) { verboseMode = vMode; }
t_bool getVerboseMode(void) { return verboseMode; }
void setVerboseFolderName(t_string vFolderName) { verboseFolderName = vFolderName; }
t_string getVerboseFolderName(void) const { return verboseFolderName; }
std::vector<Signal *> inputSignals;
std::vector<Signal *> outputSignals;
private:
bool logValue{ true };
bool firstRun{ true }; // To be deleted, 2020/02/04, the name firstTime is more comum
bool firstTime{ true };
bool terminated{ false };
t_bool verboseMode{ true };
int numberOfInputSignals{ 1 };
int numberOfOutputSignals{ 1 };
t_string verboseFolderName{ "verbose" };
};
when I make in the terminal, I receive the following error:
undefined reference to `vtable for DvQkdLdpcTxMessageProcessorReceiver'
How could I fix it? I searched a lot about the error (I tried to find pure virtual method or inline functions and ...), but no result. Thank you.
Related
I have a situation here...
I want to design a Factory where I can call a function with same name and no parameters but return different data Types. Based on the SubClassName I need to instantiate the Object.
Need help or lead on any design pattern to follow?
EDIT:
An abstract pseudo code...
class parent{
public:
virtual string getName() = 0;
//some virtual function.. not sure how to design. As the return type is dynamic.
*** getValue(){}
};
class A : public parent{
int x;
public:
virtual string getName(){ return "A";}
virtual int getValue(){retun x;}
};
class B : public parent{
string s;
public:
virtual string getName(){ return "B";}
virtual string getValue(){ return s;}
};
void main(){
string callingClass = "B";
parent * arrayPtrs[2];
arrayPtrs[0] = new A;
arrayPtrs[1] = new B;
for (loop through array, through iterator i){
if(arrayPtrs[i]->getName == callingClass ){
cout<<arrayPtrs[i]->getValue;
}
}
}
In C++ a function can only have one return type at a time, and you cannot change that dynamically.
However - as suggested by #mch - you can use template specializations. Keep in mind though, that this method is not dynamic. Your functions will be generated at compile time.
If I understood your question correctly, maybe this can be of help.
class MyObject1
{
//...
};
class MyObject2
{
//...
};
template<typename T>
struct Factory
{
constexpr static T gen();
};
template<>
struct Factory<MyObject1>
{
constexpr static MyObject1 gen()
{
return MyObject1(/*... whatever parameters you see fit ...*/);
}
};
template<>
struct Factory<MyObject2>
{
constexpr static MyObject2 gen()
{
return MyObject2(/*... whatever parameters you see fit ...*/);
}
};
int main()
{
auto myObj = Factory<MyObject1>::gen();
return 0;
}
Although this method seems fairly useless to me. You could simply call the desired constructor instead of this.
But then again, I'm not sure if this is what you thought of. If I made any mistakes please feel free, to correct me. I'll try to edit my answer best as I can.
EDIT:
To keep the virtual functionality too, the only way I can think of is type erasure: see https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Erasure
The closest I could get to what you've asked for is this:
#include <iostream>
#include <string>
#include <any>
class parent {
public:
// you can use this too but I think type checking is more handy
// see in main function
/* virtual std::string getName() const = 0; */
virtual std::any getValue() const = 0;
};
class A : public parent {
public:
typedef int value_type;
private:
value_type x;
public:
A(value_type x) :
x(x)
{}
/* virtual std::string getName() const override { return "A"; } */
virtual std::any getValue() const override
{ return this->x; }
};
class B : public parent {
public:
typedef std::string value_type;
private:
value_type s;
public:
B(const value_type& s) :
s(s)
{}
/* virtual std::string getName() const override { return "B"; } */
virtual std::any getValue() const override
{ return this->s; }
};
int main(){
using callingClass = A;
parent* arrayPtrs[2];
arrayPtrs[0] = new A(42);
arrayPtrs[1] = new B("my string");
for (unsigned i = 0; i < sizeof(arrayPtrs) / sizeof(parent*); ++i)
{
// Note:
// dynamic cast will return nullptr if $callingClass
// is not a derived class
if (dynamic_cast<callingClass*>(arrayPtrs[i]))
std::cout << std::any_cast<callingClass::value_type>(arrayPtrs[i]->getValue()) << std::endl;
}
return 0;
}
I hope this one helps.
Note, that I used dynamic_cast to check the correct type. If you know a better solution, you can use that, too. But under these circumstances I couldn't think of any better.
EDIT2:
#include <iostream>
#include <string>
#include <tuple>
class some
{
using id = size_t;
template<typename T>
struct type { static void id() { } };
template<typename T>
static id type_id() { return reinterpret_cast<id>(&type<T>::id); }
template<typename T>
using decay = typename std::decay<T>::type;
template<typename T>
using none = typename std::enable_if<!std::is_same<some, T>::value>::type;
struct base
{
virtual ~base() { }
virtual bool is(id) const = 0;
virtual base *copy() const = 0;
} *p = nullptr;
template<typename T>
struct data : base, std::tuple<T>
{
using std::tuple<T>::tuple;
T &get() & { return std::get<0>(*this); }
T const &get() const& { return std::get<0>(*this); }
bool is(id i) const override { return i == type_id<T>(); }
base *copy() const override { return new data{get()}; }
};
template<typename T>
T &stat() { return static_cast<data<T>&>(*p).get(); }
template<typename T>
T const &stat() const { return static_cast<data<T> const&>(*p).get(); }
template<typename T>
T &dyn() { return dynamic_cast<data<T>&>(*p).get(); }
template<typename T>
T const &dyn() const { return dynamic_cast<data<T> const&>(*p).get(); }
public:
some() { }
~some() { delete p; }
some(some &&s) : p{s.p} { s.p = nullptr; }
some(some const &s) : p{s.p->copy()} { }
template<typename T, typename U = decay<T>, typename = none<U>>
some(T &&x) : p{new data<U>{std::forward<T>(x)}} { }
some &operator=(some s) { swap(*this, s); return *this; }
friend void swap(some &s, some &r) { std::swap(s.p, r.p); }
void clear() { delete p; p = nullptr; }
bool empty() const { return p; }
template<typename T>
bool is() const { return p ? p->is(type_id<T>()) : false; }
template<typename T> T &&_() && { return std::move(stat<T>()); }
template<typename T> T &_() & { return stat<T>(); }
template<typename T> T const &_() const& { return stat<T>(); }
template<typename T> T &&cast() && { return std::move(dyn<T>()); }
template<typename T> T &cast() & { return dyn<T>(); }
template<typename T> T const &cast() const& { return dyn<T>(); }
template<typename T> operator T &&() && { return std::move(_<T>()); }
template<typename T> operator T &() & { return _<T>(); }
template<typename T> operator T const&() const& { return _<T>(); }
};
using any = some;
class parent {
public:
// you can use this too but I think type checking is more handy
/* virtual std::string getName() const = 0; */
virtual any getValue() const = 0;
};
class A : public parent {
public:
typedef int value_type;
private:
value_type x;
public:
A(value_type x) :
x(x)
{}
/* virtual std::string getName() const override { return "A"; } */
virtual any getValue() const override
{ return this->x; }
};
class B : public parent {
public:
typedef std::string value_type;
private:
value_type s;
public:
B(const value_type& s) :
s(s)
{}
/* virtual std::string getName() const override { return "B"; } */
virtual any getValue() const override
{ return this->s; }
};
int main(){
using callingClass = A;
parent* arrayPtrs[2];
arrayPtrs[0] = new A(42);
arrayPtrs[1] = new B("my string");
for (unsigned i = 0; i < sizeof(arrayPtrs) / sizeof(parent*); ++i)
{
// Note:
// dynamic cast will return nullptr if $callingClass
// is not a derived class
if (dynamic_cast<callingClass*>(arrayPtrs[i]))
std::cout << arrayPtrs[i]->getValue()._<callingClass::value_type>() << std::endl;
}
return 0;
}
This snipped is in case you cannot use C++17 features, and is based on:
any class
I have class MyClass that can be modified by calling setX.
I want to know if an object of MyClass has been changed by calling isChanged.
In the code below, I don’t like to add setDirty or m_dataChanged in every method that can change the state of an object.
class ChangesHolder
{
private:
bool m_isChanged;
// boost::signals2::signal<void()> m_dataChanged;
// long m_stamps;
public:
ChangesHolder()
: m_isChanged{false}
// , m_stamps{0}
{
// m_dataChanged.connect(std::bind(&ChangesHolder::setDirty, this));
}
bool isChanged() const
{
return m_isChanged;
// return (m_stamps == 0);
}
void resetChanges()
{
m_isChanged = false;
// m_stamps = 0;
}
protected:
void setDirty()
{
m_isChanged = true;
// ++m_stamps;
}
}
class MyClass : public ChangesHolder
{
private:
int m_x;
public:
void setX(int x)
{
if (m_x != x)
{
m_x = x;
setDirty();
// m_dataChanged();
}
}
}
I want to register such methods like this:
template<typename ... Funcs>
void startTrack(Funcs ... funcs)
{
auto connect = [&](auto func)
{
// connect func to setDirty
};
do_foreach(connect, funcs ...);
}
MyClass::MyClass()
{
startTrack(&MyClass::setX, &MyClass::setY);
}
How can this be done or maybe there are other ways to do it?
template<class... ArgumentType>
class IEvent
{
public:
virtual ~IEvent() = default;
virtual bool Dispatch(ArgumentType...) = 0;
};
// Event Interfaces Impl
class IMouseEvent : public IEvent<TypeMouseEvent, int, int>
{
public:
IMouseEvent() : IEvent() { }
virtual ~IMouseEvent() { }
// override to get mouse event.
virtual bool LMouseUp(unsigned x, unsigned y) { return true; }
virtual bool LMouseDown(unsigned x, unsigned y) { return true; }
virtual bool RMouseUp(unsigned x, unsigned y) { return true; }
virtual bool RMouseDown(unsigned x, unsigned y) { return true; }
virtual bool MouseMove(unsigned x, unsigned y) { return true; }
bool Dispatch(TypeMouseEvent Type, int x, int y) override;
};
class IKeyboardEvent : public IEvent<TypeKeyboardEvent, UINT_PTR>
{
public:
IKeyboardEvent() : IEvent() { }
virtual ~IKeyboardEvent() { }
// override to get keyboard event.
virtual bool vKeyDown(UINT_PTR vKeyCode) { return true; }
virtual bool vKeyUp(UINT_PTR vKeyCode) { return true; }
virtual bool KeyCode(UINT_PTR KeyCode) { return true; }
bool Dispatch(TypeKeyboardEvent Type, UINT_PTR Key) override;
};
template<class EventType, class... ArguementType>
class IEventHandler
{
protected:
// Cancelable Events
std::vector<EventType*> m_PreEvents;
// None-Cancelable Events
std::vector<EventType*> m_Events;
public:
void RegisterPreEvent(EventType* eventObject) { m_PreEvents.push_back(eventObject); }
void RegisterEvent(EventType* eventObject) { m_Events.push_back(eventObject); }
bool DispatchEvent(ArguementType... Arguments);
};
template <class EventType, class ... ArgumentType>
inline bool IEventHandler<EventType, ArgumentType...>::DispatchEvent(ArgumentType... Arguments)
{
bool isSuccessed = true;
auto tryDispatch = [Arguments...](auto begin, auto end, bool fKeepExcute) -> bool
{
for (auto Iterator = begin; Iterator != end; ++Iterator)
{
if ((*Iterator)->Dispatch(Arguments...) == false && fKeepExcute == false)
{
return false;
}
}
return true;
};
if (tryDispatch(m_PreEvents.begin(), m_PreEvents.end(), false))
{
isSuccessed = true;
tryDispatch(m_Events.begin(), m_Events.end(), true);
}
return isSuccessed;
}
I want to get ArgumentType from IMouseEvent or IKeyboardEvent from IEventHandler.
How can I get packed variadic template types from IMouseEvent?
Im actually using like IMouseEventHandler : public IEventHandler<IMouseEvent, TypeMouseEvent, int, int>
just like class IMouseEventHandler : public IEventHandler<IMouseEvent> to get packed variadic template types from IMouseEvent to syncronize with DispatchEvent. (not to make duplicated DispatchEvent method)
I think you can use this code:
template<class... Args>
class IEvent
{
public:
using event_type = IEvent;
};
template <typename , typename>
struct IEventHandlerImpl;
template <typename Event, typename... Args>
struct IEventHandlerImpl<Event, IEvent<Args...>> {
Event event;
bool DispatchEvent(Args... args) {
return event.Dispatch(args...);
}
};
template <typename EventType>
struct IEventHandler
: IEventHandlerImpl <EventType, typename EventType::event_type>
{
};
You can take look at this demo
I am coding in stm32. Basically, I want to access a bool array data from another library. This is a header file of AP_Tmxk_LIDARScanner library stored data in scan.isObstacle which is a bool array. Also I made a return function named getObstacle(). Another library named AP_Tmxk_VFH to access data from getObstacle(). Is that ok? Or which is the way to copy that array in AP_Tmxk_VFH. Thanks for your help.
AP_Tmxk_LIDARScanner
class AP_Tmxk_LIDARScanner {
private:
struct{
bool isObstacle[180] = {}; //1: unsafe; 0:safe
bool available = false;
}scan;
public:
AP_Tmxk_LIDARScanner();
void init();
void update();
bool getAvailable() const{
return scan.available;
}
bool getObstacle() const{
return scan.isObstacle;
}
};
AP_Tmxk_VFH.h
class AP_Tmxk_VFH {
private:
struct{
bool Certain_Value[180] = {};
}sector;
const AP_Tmxk_LIDARScanner &_lidarscanner;
public:
// Constructor
AP_Tmxk_VFH(const AP_Tmxk_LIDARScanner &_lidarscanner);
void init();
void update();
};
AP_Tmxk_VFH.cpp
AP_Tmxk_VFH::AP_Tmxk_VFH(const AP_Tmxk_LIDARScanner &lidarscanner) :
_lidarscanner(lidarscanner)
{}
void AP_Tmxk_VFH::update()
{
if(_lidarscanner.getAvailable()){
sector.Certain_Value = _lidarscanner.getObstacle()
}
}
Here I modfiy my code format.
AP_Tmxk_LIDARScanner.h
class AP_Tmxk_LIDARScanner {
private:
struct{
bool isObstacle[180]= {}; //1: unsafe; 0:safe
bool available = false;
}scan;
public:
AP_Tmxk_LIDARScanner();
void init();
void update();
bool getAvailable() const{
return scan.available;
}
void getObstacle(int (&array)[180]);
};
AP_Tmxk_LIDARScanner.cpp
void AP_Tmxk_LIDARScanner::getObstacle(int (&array)[180])
{
for(int i=0; i<180; i++){
if(scan.isObstacle[i]){
array[i] = (array[i]+1 >= 5) ? 5 : array[i]+1;
}
else{
array[i] = (array[i]-1 >= 0) ? array[i]-1 : 0;
}
}
}
AP_Tmxk_VFH.h
class AP_Tmxk_VFH {
private:
struct{
int Certain_Value[180] = {};
}sector;
class AP_Tmxk_LIDARScanner &_lidarscanner;
public:
// Constructor
AP_Tmxk_VFH(class AP_Tmxk_LIDARScanner &_lidarscanner);
void init();
void update();
};
AP_Tmxk_VFH.cpp
AP_Tmxk_VFH::AP_Tmxk_VFH(class AP_Tmxk_LIDARScanner &lidarscanner) :
_lidarscanner(lidarscanner)
{}
void AP_Tmxk_VFH::update()
{
if(_lidarscanner.getAvailable()){
_lidarscanner.getObstacle(sector.Certain_Value);
}
}
I need to solve such a problem.
There is a base class and two inherited classes. The base class contains method which needs a function-pointer as a parameter. But such functions are defined in inherited classes.
class CBase;
typedef bool (CBase::*FPredicate)();
class CBase
{
public:
CBase() {}
~CBase() {}
protected:
//this method waits until 'predicate' is true or until 'timeout' ms. passed
//and returns true if 'predicate' is true eventually
bool WaitEvent(FPredicate predicate, int timeout)
{
bool result = false;
int time1 = GetTickCount();
int time2;
bool isEnd = false;
while(!isEnd)
{
result = isEnd = (this->*predicate)();
time2 = GetTickCount();
if(time2 - time1 > timeout && !isEnd)
isEnd = true;
}
return result;
}
};
class CChildA : public CBase
{
protected:
bool a1() {/*some work*/}
bool a2() {/*some work*/}
void a_main()
{
...
WaitEvent(&CChildA::a1, 100);
...
WaitEvent(&CChildA::a2, 100);
...
}
};
class CChildB : public CBase
{
protected:
bool b1() {/*some work*/}
bool b2() {/*some work*/}
void b_main()
{
...
WaitEvent(&CChildB::b1, 100);
...
WaitEvent(&CChildB::b2, 100);
...
}
};
MSVC 2005 compiler gives an error on WaitEvent calls:
error C2664: 'CBase::WaitEvent' : cannot convert parameter 1 from 'bool (__thiscall CChildA::* )(void)' to 'FPredicate'
A question is: how shall I change the code to make it work? will it be safe to rewrite WaitEvent call as
WaitEvent((FPredicate)(&CChildA::a1), 100)?
In this case compiler tells of no error but is it safe? Or is there a better way of solving a problem?
Thank you in advance.
The problem is that the implicitly passed this differs in type. Either you cast it, but that will probably fail in the presence of multiple inheritance. A better & more robust solution would be to change the signature to:
template< typename T >
bool WaitEvent( bool ( T::*predicate )(), int timeout ) { ... }
You can do it using a template class to do a closure of your child object and its function member saving it's correct type. And then using virtual functions to let the base class calls it through usual polymorphism.
A similar mechanism is used in shared_ptr to call destructors. See: http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-1-of-n
#include <iostream>
struct CPredicateBase
{
virtual ~CPredicateBase() {}
virtual bool operator()() = 0;
};
template <class T>
struct CPredicate : public CPredicateBase
{
bool (T::*func)();
T* self;
CPredicate(T* self_, bool (T::*func_)())
: func(func_), self(self_) {}
bool operator() () { return (self->*func)(); }
};
class CBase
{
public:
bool WaitEvent(CPredicateBase& predicate, int imeout)
{
/// just to show the call
bool b = predicate();
std::cout << "WaitEvent called predicate() => " << b << std::endl;
return b;
}
};
class CChildA : public CBase
{
public:
bool a1() { return false; }
bool a2() { return true; }
void a_main()
{
std::cout << "CChildA::a_main()" << std::endl;
CPredicate<CChildA> caller1(this, &CChildA::a1);
bool ra1 = WaitEvent(caller1, 100);
CPredicate<CChildA> caller2(this, &CChildA::a2);
bool ra2 = WaitEvent(caller2, 100);
}
};
class CChildB : public CBase
{
public:
bool b1() { return false; }
bool b2() { return true; }
void b_main()
{
std::cout << "CChildB::b_main()" << std::endl;
CPredicate<CChildB> caller1(this, &CChildB::b1);
bool rb1 = WaitEvent(caller1, 100);
CPredicate<CChildB> caller2(this, &CChildB::b2);
bool rb2 = WaitEvent(caller2, 100);
}
};
int main(int argc, char const* argv[])
{
CChildA cA;
CChildB cB;
cA.a_main();
cB.b_main();
return 0;
}