Make a C++ overloaded operator a function pointer -
is there way overload operator (specifically, operator >>) function pointer , assign function @ run-time? want able @ file @ run-time ascertain format of file, assign correct function pointer operator make work desired. assign correct function in constructor, before operator called. realize there other (perhaps easier) ways same thing, i'm wondering if possible.
here's tried:
bool flag; // in global scope - set in main() class myclass { private: int data; friend istream & function1(istream & in, myclass & c); friend istream & function2(istream & in, myclass & c); public: myclass() :data(0) {operator>>=((flag)?&function1:&function2);} friend istream& (*operator>>)(istream & in, c & c); }; // function1 , function2 definitions go here int main (int argc, char **argv) { if (argc > 2) flag = ((atoi(argv[1]) > 1) ? 1 : 0); myclass mcinstance; ifstream in(argv[2]); in >> mcinstance; return 0; }
i error looks this:
error: declaration of ‘operator>>’ non-function
you can't redefine meaning of actual function, including operators, @ run-time directly: functions immutable entities. can do, however, delegate within function, including user-defined operator, different function using pointer function. example:
std::istream& std::operator>> (std::istream& in, myclass& object) { return flag? function1(in, object): function2(in, object); }
if want delegate through function pointer, e.g., per object, set function pointer in object , delegate through that:
class myclass { fried std::istream& operator>> (std::istream&, myclass&); std::istream& (*d_inputfunction)(std::istream&, myclass&); public: myclass(): d_inputfunction(flag? &function1: &function2) {} // ... }; std::istream& operator>> (std::istream& in, myclass& object) { return (object.d_inputfunction)(in, object); }
Comments
Post a Comment