Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a C++ overloaded operator a function pointer

Is there a way to overload an operator (specifically, operator >>) as a function pointer and then assign it a function at run-time? I want to be able to look at a file at run-time to ascertain the format of the file, then assign the correct function pointer to the operator to make it work as desired. I would assign the correct function in the constructor, before the operator would be called. I realize there are other (perhaps easier) ways to do the same thing, but I'm wondering if this is possible.

Here's what I 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 and 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 get an error that looks like this:

error: declaration of ‘operator>>’ as non-function

like image 446
Zack Sheffield Avatar asked Nov 23 '22 16:11

Zack Sheffield


1 Answers

You can't redefine the meaning of any actual function, including operators, at run-time directly: functions are immutable entities. What you can do, however, is to delegate within the function, including a user-defined operator, to a different function using a pointer to a function. For example:

std::istream&
std::operator>> (std::istream& in, MyClass& object) {
    return Flag? function1(in, object): function2(in, object);
}

If you want to delegate through a function pointer, e.g., per object, you could set the function pointer up in your object and 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);
}
like image 110
Dietmar Kühl Avatar answered Jun 12 '23 08:06

Dietmar Kühl