-2

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());
}
yooo123
  • 67
  • 1
  • 1
  • 11
  • 1
    "why does it work since I pass stringToUp to transform without any parameters?" `std::transform` does this, not you. – DimChtz Nov 01 '17 at 10:36
  • 1
    `std::transform()` calls the `operator()` of the object you pass. But why not pass `std::toupper` to `std::transform()`? – Peter Nov 01 '17 at 10:38
  • @Peter as I said, it is just an exercise to understand how functors work – yooo123 Nov 01 '17 at 10:40

1 Answers1

0

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;
}
Caleth
  • 52,200
  • 2
  • 44
  • 75