6

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

  • possible duplicate of [Is it possible to get the function pointer of a built-in standard operator?](http://stackoverflow.com/questions/17644816/is-it-possible-to-get-the-function-pointer-of-a-built-in-standard-operator) – aaronman Aug 16 '13 at 00:05
  • Just make your `operator>>` function look at `Flag` and modify its behaviour accordingly. – Jonathan Potter Aug 16 '13 at 00:11
  • You can create a function pointer to an operator, but it will have a normal name to call. – Neil Kirk Aug 16 '13 at 01:59

1 Answers1

1

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);
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • @ZackSheffield: Well, I you clearly asked if you can somehow assign to the output operators. It seems, you really want to know how to overload the input operator and do from there whatever you need to do. I added examples of this can be done. – Dietmar Kühl Aug 17 '13 at 13:37