Search code examples
c++stringfunctoruppercase

function object that converts string to uppercase


I would like to make a function object that converts a string letters to uppercase so that I can pass that functor to transform() - transform(string.begin(), string.end(), string.begin(), stringToUp()); . I know I can do it otherway, it is just an exercise. Here is my code that works, but my question is why does it work since I pass stringToUp to transform without any parameters?

class stringToUp{

public:

    int operator()(int ex) {
        return toupper(ex);  // ?? 
    }
};

int main(){

string k("toupper");

    transform(k.begin(), k.end(), k.begin(), stringToUp());
}

Solution

  • stringToUp is a class. You can have an object that is a stringToUp:

    int main() {
        stringToUp toUp;
        return 0;
    }
    

    It has an operator(), so you can use objects of type stringToUp like functions

    int main() {
        stringToUp toUp;
        char x = toUp('x');
        return 0;
    }
    

    When you are writing a template, functions and function objects look the same:

    template<typename Functor>
    void transform(int& out, int in, Functor functor) {
       out = functor(in);
    }
    
    int main() {
        stringToUp toUp;
        char x, y;
        transform(x, 'x', toUp); // like "x = toUp('x');"
        transform(x, 'x', std::toupper); // like "y = std::toupper('y');"
        return 0;
    }