Dynamic function call C++ - c++

I would like to do something like this:
class Base{};
class Specialized1 : public Base
{
public:
int GetCount(){ return 1; }
};
class Specialized2 : public Base
{
public:
bool IsCorrect() { return true; }
};
class Example
{
public:
template< class ATTR_CLASS, class RETURNED_PARAMETER_CLASS >
int GetPerfectAttributeIndex( const RETURNED_PARAMETER_CLASS & perfect_parameter, ***RETURNED_PARAMETER_CLASS (*function_to_call)()*** )
{
for ( int i = 0; i < AttributeCount; ++i )
{
if ( perfect_parameter ==
static_cast< ATTR_CLASS >( MyAttributeTable[ i ] )->function_to_call() )
{
return i;
}
}
return -1;
}
Base** MyAttributeTable;
int AttributeCount;
};
And the call would be:
example.GetPerfectAttributeIndex< Specialized1, int >( 1, &Specialized1::GetCount );
So I know that this code is not working because of the part between ***
But how can I change it to make it work? Using some C++11 magic?
Thank you for any help!

The problem is that function_to_call is not a pointer to member function. You should also downcast from Base* more safe with dynamic_cast and checking against nullptr afterwards.
class Base
{
public:
virtual ~Base() = default;
};
class Specialized1 : public Base
{
public:
int GetCount() { return 1; }
};
class Specialized2 : public Base
{
public:
bool IsCorrect() { return true; }
};
class Example
{
public:
template <class ATTR_CLASS, class RETURNED_PARAMETER_CLASS>
int GetPerfectAttributeIndex(
RETURNED_PARAMETER_CLASS const& perfect_parameter,
RETURNED_PARAMETER_CLASS(ATTR_CLASS::*function_to_call)()) // added ATTR_CLASS::
{
for(int i = 0; i < AttributeCount; ++i)
{
auto ptr = dynamic_cast<ATTR_CLASS*>(MyAttributeTable[i]);
if(!ptr)
{
// handle the case of an invalid cast
}
if(perfect_parameter == (ptr->*function_to_call)()) // extra parentheses added and ->* operator used
return i;
}
return -1;
}
Base** MyAttributeTable;
int AttributeCount;
};

Related

Access child class functions from a vector of a parent class without downcasting

How can one access child class functions from a vector of a parent class without downcasting?
example:
class a {
public:
...
};
class b : public a {
double output() { // both child class have memeber function called output,
// but they return different data type.
return 0;
}
};
class c : public a {
bool output() { return false; }
};
// main
vector<a> vec;
b obj;
c obj2;
vec.push_back(obj);
vec.push_back(obj2);
for (int i = 0; i < vec.size(); i++) {
cout << vec[i].output();
}
Error:
error: no member function called "output" found in a
I have tried function overridding:
class a{
public:
auto output()
};
This approach don't work because I sometimes need to pass multiple parameters and this function doesn't allow that and will throw me the error: Function output expected 0 parameters, received x parameters.
It is possible like this
#include <iostream>
#include <vector>
struct result
{
enum
{
BOOL,
DOUBLE
} tag;
union ret {
double d;
bool b;
} r;
};
std::ostream &operator<<(std::ostream &s, const result &r)
{
switch (r.tag)
{
case result::DOUBLE:
s << r.r.d;
break;
case result::BOOL:
s << r.r.b;
break;
default:
break;
}
return s;
}
class a
{
public:
virtual result output() = 0;
};
class b : public a
{
result output() override
{
result r{result::DOUBLE, 132.};
return r;
}
};
class c : public a
{
result output() override
{
result r{result::BOOL, false};
return r;
}
};
int main(int argc, char const *argv[])
{
std::vector<a *> vec;
a *obj = new b;
a *obj2 = new c;
vec.push_back(obj);
vec.push_back(obj2);
for (int i = 0; i < vec.size(); i++)
{
std::cout << vec[i]->output() << std::endl;
}
return 0;
}
but its ugly. even more then

upcasting variable in derived class c++

How to change the type of a inherited variable in the derived class?
I have the following classes:
class Position;
class StonePosition;
class Position {
public:
Position() {}
};
class StonePosition : public Position {
int count;
public:
StonePosition(const int count) { this->count = count; }
int getCount() { return this->count; }
void setCount(int count) { this->count = count; }
friend ostream& operator<<(ostream&, StonePosition);
};
class Board {
protected:
Position* crrPos;
public:
Board() { }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
class StoneBoard : public Board {
public:
StoneBoard(const int &count) { this->crrPos=new StonePosition(count); } //<----------------
StonePosition* getCrrPos() { return (StonePosition*)crrPos; }
void setCrrPos(StonePosition* pos) { crrPos=pos; }
};
Place in which the problem is marked by an arrow. I need to change the type of a variable from Position to StonePosition in the StoneBoard class. I found an option that can be used upcasting, but it works only within a single method, and I need to change the variable for the entire class.
The problem was solved, look at my answer.
The variable "crrPos" is not of type Position it is of type pointer to Position and this is significant because a pointer to Position can point to a Position or a class derived from Position without losing anything.
If you design your classes well, and make use of virtual functions, you can usually avoid the need to upcast entirely.
#include <iostream>
class Base {
public:
virtual void foo() { std::cout << "Base::foo()\n"; }
virtual bool isDerived() const { return false; }
};
class Derived : public Base {
public:
void foo() override { std::cout << "Derived::foo()\n"; }
bool isDerived() const { return true; }
};
int main() {
Base* crrPos = new Derived;
crrPos->foo();
bool isDerived = crrPos->isDerived();
std::cout << isDerived << '\n';
delete crrPos;
}
Live demo: http://ideone.com/UKcBaA
The problem has been solved, I just use the projection ((StonePosition*)Position*):
#include <iostream>
using namespace std;
class Position;
class StonePosition;
class Position {
public:
Position() {}
};
class StonePosition : public Position {
int count;
public:
StonePosition(const int count) { this->count = count; }
int getCount() { return this->count; }
void setCount(int count) { this->count = count; }
friend ostream& operator<<(ostream&, StonePosition);
};
template <typename TPos> class TBoard {
protected:
TPos* crrPos;
public:
TBoard() { }
TPos* getCrrPos() { return crrPos; }
void setCrrPos(TPos* pos) { crrPos=pos; }
};
class Board {
protected:
Position* crrPos;
public:
Board() { }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
class StoneBoard : public Board {
public:
StoneBoard(const int &count) { this->crrPos=new StonePosition(count); }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
int main(){
StoneBoard s(7);
cout<<((StonePosition*)s.getCrrPos())->getCount();//<----right here
system("pause");
return 0;
}
And its working nice :)

Return Generic Type data from function

I have written the following code. Where the function func() print the header and data.
class ICell
{
public:
wstring header;
virtual void Fetch() = 0;
};
template <class T>
class Cell : public ICell
{
public:
//wstring header;
T data;
void Fetch()
{
wcout<< header << L": ";
cout<<data<<endl;
}
// implementation of cell methods
};
class Row
{
public:
vector <ICell *> cells;
};
Is there any way to return the data instead of print within the function? If so, which portion of the code should be modified?
Thanks in advance.
int main()
{
Cell<int>c1;
Cell<double>c2;
c1.header = L"Roll", c1.data = 100;
c2.header = L"CGPA", c2.data = 3.5;
Row r;
r.cells.push_back(&c1);
r.cells.push_back(&c2);
vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
//checkt type of it wherther it points Cell<int> or Cell<double>
}
return 0;
}
I have changed my question here. In main() inside the loop how can I check the object type which is pointed by 'it'?
Thank you all for patience and helping me :)
Easiest way is to use dynamic_cast:
vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
Cell<int>* cell_i= dynamic_cast<Cell<int>*>(*it);
if(cell_i)
{
do_something(cell_i->data);
continue;
}
Cell<double>* cell_d= dynamic_cast<Cell<double>*>(*it);
if(cell_d)
{
do_something(cell_d->data);
continue;
}
}
Better way is to use visitor pattern:
class ICellVisitor; //declaration for ICell to understand ICell* pointer
class ICell
{ public:
~ICell(){}; // important
std::wstring header;
virtual void visit( ICellVisitor* v ) = 0;
};
template <class T> class Cell; // for Cell<T>* pointer
class ICellVisitor
{ public:
virtual void visit( Cell<int>* c ) = 0;
virtual void visit( Cell<double>* c ) = 0;
virtual void visit( Cell<float>* c ) = 0;
virtual void visit( Cell<long long>* c ) = 0;
};
template <class T> class Cell : public ICell
{ public:
//wstring header;
T data;
void visit( ICellVisitor* v )
{
std::wcout<< header << L": ";
v->visit(this);
}
// implementation of cell methods
};
class Row
{ public:
std::vector <ICell *> cells;
};
Now we need definition of concrete visitor to keep the algorithm for each type:
class MyCellVisitor: public ICellVisitor
{ public:
void visit( Cell<int>* c ){
std::wcout<<"(int)"<<c->data<<std::endl;
}
void visit( Cell<double>* c ){
std::wcout<<"(double)"<<c->data<<std::endl;
}
void visit( Cell<float>* c ){
std::wcout<<"(float)"<<c->data<<std::endl;
}
void visit( Cell<long long>* c ){
std::wcout<<"(long long)"<<c->data<<std::endl;
}
};
int main()
{
Cell<int>c1;
Cell<double>c2;
c1.header = L"Roll", c1.data = 100;
c2.header = L"CGPA", c2.data = 3.5;
Row r;
r.cells.push_back(&c1);
r.cells.push_back(&c2);
MyCellVisitor visitor;
std::vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
(*it)->visit( &visitor );
}
return 0;
}

Member-function pointers and inheritance

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;
}

Dynamic Object in C++?

I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
Note that obviously, somethingIJustMadeUp is not actually a defined member of MyType but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
or
if(myObject["somethingIJustMadeUp"]);
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
C++Script is what you want!
Example:
#include <cppscript>
var script_main(var args)
{
var x = object();
x["abc"] = 10;
writeln(x["abc"]);
return 0;
}
and it's a valid C++.
You can do something very similar with std::map:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
Now if you want generic value types, then you can use boost::any as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
If you use boost::any, then you can know the actual type of value it holds, by calling .type() as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.
This can be a solution, using RTTI polymorphism
#include <map>
#include <memory>
#include <iostream>
#include <stdexcept>
namespace dynamic
{
template<class T, class E>
T& enforce(T& z, const E& e)
{ if(!z) throw e; return z; }
template<class T, class E>
const T& enforce(const T& z, const E& e)
{ if(!z) throw e; return z; }
template<class Derived>
class interface;
class aggregate;
//polymorphic uncopyable unmovable
class property
{
public:
property() :pagg() {}
property(const property&) =delete;
property& operator=(const property&) =delete;
virtual ~property() {} //just make it polymorphic
template<class Interface>
operator Interface*() const
{
if(!pagg) return 0;
return *pagg; //let the aggregate do the magic!
}
aggregate* get_aggregate() const { return pagg; }
private:
template<class Derived>
friend class interface;
friend class aggregate;
static unsigned gen_id()
{
static unsigned x=0;
return enforce(++x,std::overflow_error("too many ids"));
}
template<class T>
static unsigned id_of()
{ static unsigned z = gen_id(); return z; }
aggregate* pagg;
};
template<class Derived>
class interface: public property
{
public:
interface() {}
virtual ~interface() {}
unsigned id() const { return property::id_of<Derived>(); }
};
//sealed movable
class aggregate
{
public:
aggregate() {}
aggregate(const aggregate&) = delete;
aggregate& operator=(const aggregate&) = delete;
aggregate(aggregate&& s) :m(std::move(s.m)) {}
aggregate& operator=(aggregate&& s)
{ if(this!=&s) { m.clear(); std::swap(m, s.m); } return *this; }
template<class Interface>
aggregate& add_interface(interface<Interface>* pi)
{
m[pi->id()] = std::unique_ptr<property>(pi);
static_cast<property*>(pi)->pagg = this;
return *this;
}
template<class Inteface>
aggregate& remove_interface()
{ m.erase[property::id_of<Inteface>()]; return *this; }
void clear() { m.clear(); }
bool empty() const { return m.empty(); }
explicit operator bool() const { return empty(); }
template<class Interface>
operator Interface*() const
{
auto i = m.find(property::id_of<Interface>());
if(i==m.end()) return nullptr;
return dynamic_cast<Interface*>(i->second.get());
}
template<class Interface>
friend aggregate& operator<<(aggregate& s, interface<Interface>* pi)
{ return s.add_interface(pi); }
private:
typedef std::map<unsigned, std::unique_ptr<property> > map_t;
map_t m;
};
}
/// this is a sample on how it can workout
class interface_A: public dynamic::interface<interface_A>
{
public:
virtual void methodA1() =0;
virtual void methodA2() =0;
};
class impl_A1: public interface_A
{
public:
impl_A1() { std::cout<<"creating impl_A1["<<this<<"]"<<std::endl; }
virtual ~impl_A1() { std::cout<<"deleting impl_A1["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_A2: public interface_A
{
public:
impl_A2() { std::cout<<"creating impl_A2["<<this<<"]"<<std::endl; }
virtual ~impl_A2() { std::cout<<"deleting impl_A2["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
};
class interface_B: public dynamic::interface<interface_B>
{
public:
virtual void methodB1() =0;
virtual void methodB2() =0;
};
class impl_B1: public interface_B
{
public:
impl_B1() { std::cout<<"creating impl_B1["<<this<<"]"<<std::endl; }
virtual ~impl_B1() { std::cout<<"deleting impl_B1["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_B2: public interface_B
{
public:
impl_B2() { std::cout<<"creating impl_B2["<<this<<"]"<<std::endl; }
virtual ~impl_B2() { std::cout<<"deleting impl_B2["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
};
int main()
{
dynamic::aggregate agg1;
agg1 << new impl_A1 << new impl_B1;
dynamic::aggregate agg2;
agg2 << new impl_A2 << new impl_B2;
interface_A* pa = 0;
interface_B* pb = 0;
pa = agg1; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
agg2 = std::move(agg1);
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
return 0;
}
tested with MINGW4.6 on WinXPsp3
Yes it is terrible. :D
It had been done numerous times to different extents and success levels.
QT has Qobject from which everything related to them decends.
MFC has CObject from which eveything decends as does C++.net
I don't know if there is a way to make it less bad, I guess if you avoid multiple inheritance like the plague (which is otherwise a useful language feature) and reimplement the stdlib it would be better. But really if that is what you are after you are probably using the wrong language for the task.
Java and C# are much better suited to this style of programming.
#note if I have read your question wrong just delete this answer.
Check out Dynamic C++