How to restructure this code without duplicating too much code? - c++

class
{
public:
void func(const int val, const bool flag)
{
if(flag)
{
while(!lower.empty() && val <= lower.top())
{
// do a bunch of stuff with lower
}
}
else
{
while(!higher.empty() && val >= higher.top())
{
// do a bunch of stuff with higher, but it's the same stuff as would've done
// for lower
}
}
}
private:
std::stack<int> lower;
std::stack<int> higher;
}
I'm trying to figure out a better way to write the clauses because currently, I have a lot of duplicate code in both. The only difference is one clause operates on lower and the other on higher and the <= in the first clause is changed to >= higher in the second one.
I could wrap the clause in a helper function and call it in each clause (and pass in the lower and higher as an argument), e.g.,
class
{
public:
void func(const int val, const bool flag)
{
if(flag)
{
helper(lower, comparer);
}
else
{
helper(lower, comparer);
}
}
void helper(std::stack<int> &st)
{
// do a bunch of stuff with st
}
private:
std::stack<int> lower;
std::stack<int> higher;
}
I'm not sure if this is a good idea and if it is, I'm not sure how to get around the >= vs. <=. I'm hoping for suggestions on my design!

You can do something like the following:
class
{
public:
void func(const int val, const bool flag)
{
std::stack<int> *st;
bool (*compare)(int, int);
if (flag)
{
st = &lower;
compare = [](int a, int b){ return a <= b; };
}
else
{
st = &higher;
compare = [](int a, int b){ return a >= b; };
}
while (!st->empty() && compare(val, st->top()))
{
// do a bunch of stuff with *st
}
}
private:
std::stack<int> lower;
std::stack<int> higher;
}
Alternatively, using a helper would certainly work, too:
class
{
public:
void func(const int val, const bool flag)
{
if (flag)
func_helper(lower, val, std::less_equal{});
else
func_helper(higher, val, std::greater_equal{});
}
private:
std::stack<int> lower;
std::stack<int> higher;
template<typename Comparer>
void func_helper(stack<int> &st, const int val, Comparer compare)
{
while (!st.empty() && compare(val, st.top()))
{
// do a bunch of stuff with st
}
}
}

How about something like this
class
{
public:
void func(const int val, const bool flag)
{
int sign = 1;
std::stack<int>* higher_or_lower = &higher;
if(flag)
{
higher_or_lower = &lower;
sign = -1;
}
while(!higher_or_lower->empty() && sign*val >= sign*higher_or_lower->top())
{
// do a bunch of stuff with higher_or_lower
}
}
private:
std::stack<int> lower;
std::stack<int> higher;
}
The higher_or_lower covers both stacks and the sign takes care of less than vs. greater than.

Or a bit more compact:
class C
{
public:
void func(const int val, const bool flag)
{
const std::stack<int>* st[] = {&lower, &higher};
bool (*compare[])(int, int) = { [](int a, int b) { return a <= b; } , [](int a, int b) { return a >= b; } };
while (!st[flag]->empty() && compare[flag](val, st[flag]->top()))
{
// do a bunch of stuff with *st
}
}
private:
std::stack<int> lower;
std::stack<int> higher;
};

Related

Alternate branching strategies in Gecode

I post here to ask if there is a way to alternate different strategies of branching. Let me explain, I have an efficient branching strategy which we'll call the strategy A. The biggest problem is that the strategy A cannot be used that often. So when I cannot use the strategy A, I use another strategy, which I'll call the strategy B, which is less efficient.
The documentation says that:
Brancher order. Creating a brancher registers it with its home space. A space maintains a queue of its branchers in that the brancher that is registered first is also used first for
branching. The first brancher in the queue of branchers is referred to as the current brancher.
So, I supposed that if I post the brancher A then the brancher B, the brancher A will has priority and each time the status of A says there is no branching to do, the brancher B will be used. Seems like I was wrong because when the status of a brancher return false, it is never called again.
Here is a "minimal example":
#include <gecode/minimodel.hh>
#include <iostream>
using namespace Gecode;
using namespace std;
class MyChoice : public Choice {
public:
int pos; // Position of the variable
int val; // Value of to assign
MyChoice(const Brancher& b, int pos0, int val0)
: Choice(b,2), pos(pos0), val(val0) {}
// Report size occupied
virtual size_t size(void) const {
return sizeof(*this);
}
// Archive into e
virtual void archive(Archive& e) const {
Choice::archive(e);
e << pos << val;
}
};
class BranchA : public Brancher {
protected:
ViewArray<Int::IntView> x;
public:
BranchA(Home home, ViewArray<Int::IntView>& x0)
: Brancher(home), x(x0) {}
static void post(Home home, ViewArray<Int::IntView>& x) {
(void) new (home) BranchA(home,x);
}
virtual size_t dispose(Space& home) {
(void) Brancher::dispose(home);
return sizeof(*this);
}
BranchA(Space& home, bool share, BranchA& b)
: Brancher(home,share,b) {
x.update(home,share,b.x);
}
virtual Brancher* copy(Space& home, bool share) {
return new (home) BranchA(home,share,*this);
}
// status
virtual bool status(const Space& home) const {
for (int i=0; i<x.size(); i++)
if (!x[i].assigned())
return !i%2 && x[i].in(1);
return false;
}
// choice
virtual Choice* choice(Space& home) {
for (int i=0; true; i++)
if (!x[i].assigned())
return new MyChoice(*this,i,1);
GECODE_NEVER;
return NULL;
}
virtual Choice* choice(const Space&, Archive& e) {
int pos, val;
e >> pos >> val;
return new MyChoice(*this, pos, val);
}
// commit
virtual ExecStatus commit(Space& home,
const Choice& c,
unsigned int a) {
const MyChoice& pv = static_cast<const MyChoice&>(c);
int pos=pv.pos, val=pv.val;
if (a == 0)
return me_failed(x[pos].eq(home,val)) ? ES_FAILED : ES_OK;
else
return me_failed(x[pos].nq(home,val)) ? ES_FAILED : ES_OK;
}
};
void branchA(Home home, const IntVarArgs& x) {
if (home.failed()) return;
ViewArray<Int::IntView> y(home,x);
BranchA::post(home,y);
}
// BranchB //////////////////////////////////////////////////////
class BranchB : public Brancher {
protected:
ViewArray<Int::IntView> x;
public:
BranchB(Home home, ViewArray<Int::IntView>& x0)
: Brancher(home), x(x0) {}
static void post(Home home, ViewArray<Int::IntView>& x) {
(void) new (home) BranchB(home,x);
}
virtual size_t dispose(Space& home) {
(void) Brancher::dispose(home);
return sizeof(*this);
}
BranchB(Space& home, bool share, BranchB& b)
: Brancher(home,share,b) {
x.update(home,share,b.x);
}
virtual Brancher* copy(Space& home, bool share) {
return new (home) BranchB(home,share,*this);
}
// status
virtual bool status(const Space& home) const {
for (int i=0; i<x.size(); i++)
if (!x[i].assigned())
return i%2 && x[i].in(2);
return false;
}
// choice
virtual Choice* choice(Space& home) {
for (int i=0; true; i++)
if (!x[i].assigned())
return new MyChoice(*this,i,2);
GECODE_NEVER;
return NULL;
}
virtual Choice* choice(const Space&, Archive& e) {
int pos, val;
e >> pos >> val;
return new MyChoice(*this, pos, val);
}
// commit
virtual ExecStatus commit(Space& home,
const Choice& c,
unsigned int a) {
const MyChoice& pv = static_cast<const MyChoice&>(c);
int pos=pv.pos, val=pv.val;
if (a == 0)
return me_failed(x[pos].eq(home,val)) ? ES_FAILED : ES_OK;
else
return me_failed(x[pos].nq(home,val)) ? ES_FAILED : ES_OK;
}
};
void branchB(Home home, const IntVarArgs& x) {
if (home.failed()) return;
ViewArray<Int::IntView> y(home,x);
BranchB::post(home,y);
}
// Minimal Space ///////////////////////////////////////
class TestSpace : public Space {
protected:
IntVarArray x;
public:
TestSpace(int size)
: x(*this, size, 0, 10) {
branchA(*this, x);
branchB(*this, x);
}
TestSpace (bool share, TestSpace& s)
: Space(share, s) {
x.update(*this, share, s.x);
}
virtual Space* copy (bool share) {
return new TestSpace(share, *this);
}
void print(std::ostream& os) {
os << "x= " << x << endl;
}
};
// Minimal Main //////////////////////:
int main (int, char**) {
// create model and search engine
TestSpace* m = new TestSpace(10);
DFS<TestSpace> e(m);
delete m;
// search and print all solutions
while (TestSpace* s = e.next()) {
s->print(cout); delete s;
}
return 0;
}
In this example, the status of the brancher A return true if the next variable to assign is on an even index and if the variable can take the value of 1 (false else). And the brancher B status return true if the next variable to assign is on an odd index and if the variable can take the value of 2 (false else).
With that code I expected to get the solutions [1, 2, 1, 2, ...] and [!1, !2, !1, !2, ...] (and others combinations like [!1, 2, 1, !2, ...]) but since the branchers are disposed when their status return false, only the two first variables have been assigned.
Is there a good way to make the brancher not being disposed after its status return false (or to alternate two differents branching strategies) or should I merge the two branchers into one ?
If it may help someone, here is the solution I used.
As advised by Patrick Trentin, I unified the control by making a third brancher which is a vector of branchers. Here is the implementation I used:
The header branchAllInOne.h:
#include <gecode/minimodel.hh>
using namespace Gecode;
using namespace std;
class BranchAllInOne : public Brancher {
protected:
// Queue of brancher (may be better with ActorLink)
vector<Actor *> queue;
// Every brancher are in the brancher
BrancherGroup group;
mutable int toChoose;
class ChoiceAndID : public Choice {
public:
// Choice of the brancher used
Choice* c;
/// ID of brancher used
unsigned int id;
ChoiceAndID(const Brancher& b, Choice * c, unsigned int id);
virtual ~ChoiceAndID();
virtual size_t size(void) const ;
virtual void archive(Archive& e) const ;
};
public:
BranchAllInOne(Home home);
virtual size_t dispose(Space& home);
BranchAllInOne(Home home, bool share, BranchAllInOne& b);
virtual ~BranchAllInOne();
/**
* Check status of brancher, set toChoose value to the ID of the first
* brancher with alternative left
**/
virtual bool status(const Space&) const ;
/**
* Let the brancher of ID toChoose make the choice
*/
virtual Choice* choice(Space&);
virtual Choice* choice(const Space&, Archive& e);
/**
* Let the brancher of ID toChoose commit his choice
*/
virtual ExecStatus commit(Space& home, const Choice& _c, unsigned int a);
/// Copy brancher
virtual Actor* copy(Space& home, bool share);
/// Post brancher
static BranchAllInOne * post(Home home);
virtual void print(const Space& home,
const Choice& c,
unsigned int a,
ostream& o) const ;
void pushBrancher(Space& home, Brancher *b);
};
BranchAllInOne * branchAllInOne(Home home);
The implementation branchAllInOne.cpp:
#include "branchAllInOne.h"
static Brancher * ActorToBrancher(Actor *a);
// Choice implementation
BranchAllInOne::ChoiceAndID::ChoiceAndID(const Brancher& b, Choice * c0, unsigned int id0)
: Choice(b, c0->alternatives()),
c(c0),
id(id0){}
BranchAllInOne::ChoiceAndID::~ChoiceAndID() {
delete c;
}
size_t BranchAllInOne::ChoiceAndID::size(void) const {
return sizeof(*this) + c->size();
}
void BranchAllInOne::ChoiceAndID::archive(Archive& e) const {
Choice::archive(e);
c->archive(e);
}
BranchAllInOne::BranchAllInOne(Home home)
: Brancher(home),
toChoose(-1) {
home.notice(*this,AP_DISPOSE);
}
// brancher
BranchAllInOne * BranchAllInOne::post(Home home) {
return new (home) BranchAllInOne(home);
}
size_t BranchAllInOne::dispose(Space& home) {
home.ignore(*this, AP_DISPOSE);
size_t size = queue.size() * sizeof(Actor*);
for (unsigned int i = queue.size() ; i--;) {
size += ActorToBrancher(queue[i])->dispose(home);
}
queue.~vector();
// Making sure to kill each brancher inserted in the queue (may be useless)
group.kill(home);
(void) Brancher::dispose(home);
return sizeof(*this) + size;
}
BranchAllInOne::BranchAllInOne(Home home, bool share, BranchAllInOne& b)
: Brancher(home, share, b),
queue(b.queue.size()),
toChoose(b.toChoose){
for (unsigned int i = 0 ; i < queue.size() ; i++)
queue[i] = b.queue[i]->copy(home, share);
}
BranchAllInOne::~BranchAllInOne() {
for (unsigned int i = 0 ; i < queue.size() ; i++) {
delete queue[i];
}
queue.~vector();
}
Actor* BranchAllInOne::copy(Space& home, bool share){
return new (home) BranchAllInOne(home, share, *this);
}
// status
bool BranchAllInOne::status(const Space& s) const {
for (unsigned int i = 0 ; i < queue.size() ; i++) {
if (ActorToBrancher(queue[i])->status(s)) {
toChoose = i;
return true;
}
}
std::cout << std::endl;
return false;
}
// choice
Choice* BranchAllInOne::choice(Space& s) {
ChoiceAndID* res = new ChoiceAndID(*this,
const_cast<Choice *>(ActorToBrancher(queue[toChoose])->choice(s)),
toChoose);
toChoose = -1;
return res;
}
Choice* BranchAllInOne::choice(const Space& s, Archive& e) {
return new ChoiceAndID(*this,
const_cast<Choice *>(ActorToBrancher(queue[toChoose])->choice(s, e)),
toChoose);
}
// Perform commit for choice \a _c and alternative \a a
ExecStatus BranchAllInOne::commit(Space& home, const Choice& c, unsigned int a) {
const BranchAllInOne::ChoiceAndID& ch = static_cast<const BranchAllInOne::ChoiceAndID&>(c);
return ActorToBrancher(queue[ch.id])->commit(home, const_cast<Choice&>(*ch.c), a);
}
void BranchAllInOne::print(const Space& home,
const Choice& c,
unsigned int a,
ostream& o) const {
const BranchAllInOne::ChoiceAndID& ch = static_cast<const BranchAllInOne::ChoiceAndID&>(c);
o << ch.id << ": ";
ActorToBrancher(queue[ch.id])->print(home, *(ch.c), a, o);
}
void BranchAllInOne::pushBrancher(Space &home, Brancher *b) {
queue.push_back(b);
group.move(home, *b);
}
static Brancher * ActorToBrancher(Actor *a) {
return dynamic_cast<Brancher *>(a);
}
// end of BranchAllInOne implementation
BranchAllInOne* branchAllInOne(Home home) {
if (home.failed()) return NULL;
return BranchAllInOne::post(home);
}
I've made some modifications to get a pointer to branchers I want to put in the vector (that include the post function of each branchers):
brancherA example:
BranchA * BranchA::post(Home home, ViewArray<Int::IntView>& x) {
return new (home) BranchA(home,x);
}
BranchA * branchA(Home home, const IntVarArgs& x) {
if (home.failed()) return NULL;
ViewArray<Int::IntView> y(home,x);
return BranchA::post(home,y);
}
The space has also been modified:
TestSpace::TestSpace(int size)
: x(*this, size, 0, 10) {
BranchAllInOne * b = branchAllInOne(*this);
b->pushBrancher(*this, branchA(*this, x));
b->pushBrancher(*this, branchB(*this, x));
}
I tested it with and without Gist and only got a memory leak of a pointer for each brancher put in the vector (here only two). A small problem remain is that branchers put in the vector are also scheduled after the third brancher stoped (but their status return false).

2D Vectors Segmentation Fault:push_back

I am trying to solve a problem dealing with 2d vectors array.FunClass gets two parameters, number of sets and the lines per set.
The problem is whenever update_mytable function is being called a segmentation fault error pops up.During a quick search on stackoverflow I read that in most cases the issue for the seg-fault is because we are trying to access to a non-existed vector.But I don't think what I have the same issue here.
using std::vector;
typedef vector<mytable_entry>::iterator mytable_iter;
struct mytable_entry
{
int x_entry;
int y_entry;
};
mytable_entry new_mytable_entry(int new_ip, int new_target) {
mytable_entry new_entry;
new_entry.ip_entry = new_ip;
new_entry.target_entry = new_target;
return new_entry;
}
class FunClass : public BaseClass
{
public:
FunClass(unsigned mytable_sets, unsigned mytable_lines_per_set)
: table_sets(mytable_sets), table_assoc(mytable_lines_per_set)
{
mytable_table = vector< vector<mytable_entry> > (table_sets,vector< mytable_entry> (table_assoc));
}
~FunClass() {
/* Vectors will be decontructed automatially out of scope */
}
virtual bool predict(int x, int y) {
/* If mytable_entry exist return true, else false */
unsigned mytable_set_index = x % table_sets;
if (find_mytable_entry(mytable_table[mytable_set_index])) {
return true;
} else {
return false;
}
}
virtual void update(bool val1, bool val2, int x, int y) {
unsigned mytable_set_index = x % table_sets;
if (val1 == val2){
update_mytable_table(mytable_table[mytable_set_index],ip,target_entry,table_assoc);
}
void update_mytable(vector<mytable_entry> & mytable_set, int x, int y,unsigned table_assoc){
mytable_entry new_entry = new_mytable_entry(ip,target);
mytable_set.push_back(new_entry);
if (mytable_set.size() > table_assoc){
mytable_set.erase(mytable_set.begin());
}
}
bool find_mytable_entry(vector<mytable_entry> & mytable_set, int x) {
mytable_iter iter;
for (iter = mytable_set.begin(); iter != mytable_set.end(); iter++){
if ((*iter).ip_entry == ip) {
mytable_entry tmp_mytable_entry = (*iter);
mytable_set.erase(iter);
mytable_set.push_back(tmp_mytable_entry);
return true;
}
}
return false;
}
private:
vector< vector<mytable_entry> > mytable_table;
unsigned table_sets, table_assoc;
};
If I remove the mytable_set.push_back(new_entry); from update_mytable everything goes fine then.

Efficient generic buffer queue for sequential processing

I have a producer-consumer queue which is being updated by parallel programs. The queue is queried for various statistics like mean or standard deviation or variance or something else on the current queue contents. For mean, this is the code, I use
class BufferQueue {
const int nMaxQueueSize_;
int* values;
int head, tail;
double sum;
::utils::FastMutex queue_mutex;
public:
BufferQueue(const int nMaxQueueSize) :
nMaxQueueSize_(nMaxQueueSize) {
head = tail = 0;
sum = 0;
values = new int[nMaxQueueSize_];
}
void enqueue(int val) {
values[head] = val;
if ((head + 1) % nMaxQueueSize_ == tail) {
queue_mutex.lock();
sum = val.value_point - values[tail].value_point;
utils::memory_barrier();
head = (1 + head) % nMaxQueueSize_;
tail = (1 + tail) % nMaxQueueSize_;
queue_mutex.unlock();
} else {
queue_mutex.lock();
sum += val.value_point;
utils::memory_barrier();
head = (1 + head) % nMaxQueueSize_;
queue_mutex.unlock();
}
}
bool dequeue() {
if (head != tail) {
queue_mutex.lock();
sum -= values[tail].value_point;
utils::memory_barrier();
tail = (1 + tail) % nMaxQueueSize_;
queue_mutex.unlock();
return true;
} else {
sum = 0;
return false;
}
}
MarketSpreadPoint& operator[](int i) {
return values[ (tail + i) % nMaxQueueSize_ ];
}
inline int getSize() {
return (head - tail + nMaxQueueSize_) % nMaxQueueSize_;
}
inline double average() {
queue_mutex.lock();
double result = sum / getSize();
queue_mutex.unlock();
return result;
}
~BufferQueue() {
delete values;
}
};
NOTE: One important thing to remember is that only one operation is being performed. Neither do I want to repeat code by writing separate implementations like BufferQueueAverage, BufferQueueVariance etc. I want very limit code redundancy(compiler optimizations). Even conditioning on type of queue for every update seems sub-optimal.
inline double average() {
queue_mutex.lock();
if(type_is_average){
double result = sum / getSize();
}else if(type_is_variance){
/// update accordingly.
}
double result = sum / getSize();
queue_mutex.unlock();
return result;
}
What can be a good alternative to this idea ?
Note: In this implementation, if queue is full, head automatically make the tail to move forward. In other words, the oldest element is deleted automatically.
Thanks
So you want to separate the queue from the statistics. I see two possible solutions:
Use a pattern like Template Method or Strategy to factor out the dependency.
Use a template that does this.
Assuming that all statistics you gather can gathered incrementally, the latter could look similar to the following (just meant as pseudo code):
class StatisticsMean
{
private:
int n = 0;
double mean = 0.0;
public:
void addSample(int s) { ++n; mean += (s - mean) / n; }
void removeSample(int s) { ... }
double getStatistic() const { return mean; }
}
template <typename TStatistics>
class BufferQueue
{
TStatistics statistics;
...
void enqueue(int val)
{
...
statistics.addSample(val);
}
...
double getStatistic() const { return statistics.getStatistic(); }
}
The template approach gives you full compile-time optimization. You can achieve the same with the Template Method pattern. This would also allow you to have distinct names for the getters (getStatistic() in the above example).
This could look similar to this:
class AbstractBufferQueue
{
virtual void addSample(int s) = 0;
virtual void removeSample(int s) = 0;
void enqueue(int val)
{
...
addSample(val);
}
}
class BufferQueueAverage : public AbstractBufferQueue
{
int n;
double mean;
void addSample(int s) { ++n; mean += (s - mean) / n; }
void removeSample(int s) { ... }
double getAverage() const { return mean; }
}
One way to do what you're asking is by using template classes.
First, decide on a common interface that an accumulator will have. It might be something like:
class accumulator
{
public:
typedef double value_type;
public:
void push(int v); // Called when pushing a new value.
void pop(int v); // Called when popping a new value;
value_type result(size_t n) const; // Returns the current accumulation.
};
As a special case, mean_accumulator could be this:
class mean_accumulator
{
public:
typedef double value_type;
public:
mean_accumulator() : m_sum{0} {}
void push(int v) { m_sum += v; }
void pop(int v); { m_sum -= v; }
double result(size_t n) const { return m_sum / n; };
private:
int m_sum;
};
Now, parameterize your queue by Accumulator, and call it when necessary (while you're at it, note that boost::circular_buffer has much of what you need for the implementation:
template<class Accumulator>
class queue
{
private:
boost::circular_buffer<int> m_buf;
std::mutex m_m;
public:
void push(int v)
{
// Lock the mutex, push to the circular buffer, and the accumulator
}
bool pop()
{
// Lock the mutex; if relevant, update the accumulator and pop the circular buffer
}
typename Accumulator::value_type result() const
{
// Lock the mutex and return the accumulator's result.
}
};

Function returning function pointer from table as a parameter

I have been reading for a while, but today I can't figure someting out and find a solution.
How to return a function pointer from a function table as parameter? All similair solutions don't work for this one and end up not compiling.
I have tried a lot of methods but the compiler always returns with errors like:
function returning function is not allowed solution (when using typedef void (*func)();)
As NO parameters have to be passed into the final routine it should be possible.
My simplified example:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
struct ScanListStruct
{
int Value;
void (*Routine)(void);
}
const ScanListStruct DoList[] =
{
{1, PrintOne},
{2, PrintTwo}
}
bool GetRoutine(void *Ptr, int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value = Nr)
{
Ptr = DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
void main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
There a few things wrong with the code;
Syntax errors (missing ; etc.)
main must return int
GetRoutine should accept the function pointer by reference, not just a void* pointer to anything
if condition should contain an equality test, not an assignment
As follows, works as expected;
void PrintOne(void) { printf("One"); };
void PrintTwo(void) { printf("Two"); };
struct ScanListStruct
{
int Value;
void (*Routine)(void);
};
const ScanListStruct DoList[] =
{
{1, &PrintOne},
{2, &PrintTwo}
};
bool GetRoutine(void (*&Ptr)(), int Nr)
{
for (int x =0; x<=1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = *DoList[(x)].Routine;
//((*DoList[(x)].Routine)()); // Original Working and executing version!
return true;
}
}
return false;
}
int main(void)
{
int y = 1;
void (*RoutineInMain)(); // Define
if (GetRoutine( RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
}
Prints One.
You have lots of errors in your code. Like here you put the comas at the wrong place:
void PrintOne(void) { printf("One")};
void PrintTwo(void) { printf("Two")};
It should be
void PrintOne(void) { printf("One");}
void PrintTwo(void) { printf("Two");}
And here you are using the wrong operator, = instead of ==.
if (DoList[x].Value = Nr)
When the argument Ptr is a pointer, and that is passed by value, so the value assigned in the function will not be available when the function returns.
This is how your code should be:
void PrintOne(void) { printf("One"); }
void PrintTwo(void) { printf("Two"); }
typedef void(*prototype)();
struct ScanListStruct
{
int Value;
prototype Routine;
};
const ScanListStruct DoList[] =
{
{ 1, PrintOne },
{ 2, PrintTwo }
};
bool GetRoutine(prototype &Ptr, int Nr)
{
for (int x = 0; x <= 1; x++)
{
if (DoList[x].Value == Nr)
{
Ptr = DoList[(x)].Routine;
return true;
}
}
return false;
}
int main()
{
int y = 1;
prototype RoutineInMain; // Define
if (GetRoutine(RoutineInMain, y) == true) // get the address
{
RoutineInMain(); // Execute the function
}
return 0;
}

Transient Copy Constructor weirdness

I've got this here class defined in a header file:
class E_IndexList {
public:
E_UIntegerList* l;
inline void *data() { // retrieve packed data: stride depends on type (range)
return l->data();
}
inline void insert(unsigned value) {
if (value > maxval[l->range]) {
promote();
insert(value);
} else {
l->push_back(value);
}
}
inline size_t size() {
return l->size();
}
inline unsigned long get(int index) {
return l->get(index);
}
void promote() {
if (l->range == E_UIntegerList::e_byte) {
E_UShortList *new_short_list = new E_UShortList(*((E_UByteList*)l));
delete l;
l = new_short_list;
} else if (l->range == E_UIntegerList::e_short) {
E_UIntList *new_int_list = new E_UIntList(*((E_UShortList*)l));
delete l;
l = new_int_list;
} else ASSERT(false);
}
// start off with bytes by default
E_IndexList() {
l = new E_UByteList;
}
E_IndexList(E_UIntegerList::int_bits range) {
switch(range) {
case E_UIntegerList::e_byte:
l = new E_UByteList;
break;
case E_UIntegerList::e_short:
l = new E_UShortList;
break;
case E_UIntegerList::e_int:
l = new E_UIntList;
break;
default:
ASSERT(false);
break;
}
}
E_IndexList(const E_IndexList& cpy) { // copy ctor
switch(cpy.l->range) {
case E_UIntegerList::e_byte:
l = new E_UByteList(((E_UByteList*)cpy.l)->list);
break;
case E_UIntegerList::e_short:
l = new E_UShortList(((E_UShortList*)cpy.l)->list);
break;
case E_UIntegerList::e_int:
l = new E_UIntList(((E_UShortList*)cpy.l)->list);
break;
default:
ASSERT(false);
break;
}
}
~E_IndexList() {
delete l;
}
};
Here are some more classes it makes use of:
static const unsigned long maxval[] = {0xff,0xffff,0xffffffff};
class E_UIntegerList {
public:
enum int_bits {e_byte = 0, e_short = 1, e_int = 2};
virtual ~E_UIntegerList() {}
int_bits range;
virtual void push_back(int i) = 0;
virtual void *data() = 0;
virtual size_t size() = 0;
virtual unsigned long get(int index) = 0;
};
struct E_UByteList:public E_UIntegerList {
std::vector<unsigned char> list;
E_UByteList() {
range = e_byte;
}
E_UByteList(const std::vector<unsigned char>& copy) {
list = copy;
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
struct E_UShortList:public E_UIntegerList {
std::vector<unsigned short> list;
E_UShortList() {
range = e_short;
}
E_UShortList(const std::vector<unsigned short>& copy) {
list = copy;
}
E_UShortList(const E_UByteList& promotee) {
range = e_short;
list.assign(promotee.list.begin(),promotee.list.end()); // assignment should be compatible
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
struct E_UIntList:public E_UIntegerList {
std::vector<unsigned int> list;
E_UIntList() {
range = e_int;
}
E_UIntList(const std::vector<unsigned int>& copy) {
list = copy;
}
E_UIntList(const E_UShortList& promotee) {
range = e_int;
list.assign(promotee.list.begin(),promotee.list.end());
}
inline void push_back(int i) {
list.push_back(i);
}
inline void *data() { return list.data(); }
inline size_t size() { return list.size(); }
inline unsigned long get(int index) { return list[index]; }
};
Now the way that I use this class is I have a std::vector<E_IndexList> that I use as a container of index lists.
The strange behavior is that when I run the program sometimes it has no problems and sometimes it asserts false.
So this is a big red flag for me because something super fishy is going on. I will very likely end up abandoning the entire E_IndexList until I start working on game netcode which is a long ways off. But, I'd like to know what's going on here.
Every ctor I have sets the range to a valid value out of the enum in E_UIntegerList, so how could that assertion ever get tripped? And I can't begin to come up with an explanation of why the behavior is inconsistent. The test that calls this code is not multi-threaded.
Your E_UByteList from-vector constructor does not set the range value.
The entire design is a bit shoddy; you should learn how to use constructor initializer lists, and I would probably endow the base class with a protected constructor that sets the range value and which can be invoked from within the derived constructors' initializers.
You didn't define an assignment operator. See rule of three.
Your constructors such as this one:
E_UByteList(const std::vector<unsigned char>& copy) {
list = copy;
}
do not initialise range from the parent E_UIntegerList class.