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

4

1 回答 1

1

您不能在运行时直接重新定义任何实际函数(包括运算符)的含义:函数是不可变的实体。但是,您可以做的是在函数内(包括用户定义的运算符)使用指向函数的指针委托给不同的函数。例如:

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

如果你想通过函数指针进行委托,例如,每个对象,你可以在你的对象中设置函数指针并通过它进行委托:

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);
}
于 2013-08-16T00:12:01.697 回答