-1

It looks like plus() predefined functor should work for strings as it devolves to using the operator+. However this does not compile.

   string one="one", two="two";
   string result=std::plus<string>(one,two);

Why?

Mikhail
  • 173
  • 6
  • 1
    Obviously because there's no `main` and missing includes. But in all seriousness, your question would definitely be better if you [edit]ed it to include a [mcve] (i.e. add the includes, chuck in a `main`) AND show the actual error the compiler gives you. Doing so would help people wanting to help you. – Tas Feb 28 '19 at 04:09
  • Not at all a duplicate, but [this](https://stackoverflow.com/questions/35568541/how-stdtransform-and-stdplus-work-together) should actually answer your question – Tas Feb 28 '19 at 04:13
  • it does not. Somebody has to actually answer this one. – Mikhail Feb 28 '19 at 04:16
  • 2
    It doesn't work for string for the same reason it wouldn't work for int. You're using it incorrectly. – Retired Ninja Feb 28 '19 at 04:19
  • ah, oh. my bad. Sorry. Thank you! – Mikhail Feb 28 '19 at 04:34
  • Possible duplicate of [How std::transform and std::plus work together?](https://stackoverflow.com/questions/35568541/how-stdtransform-and-stdplus-work-together) – BDL Feb 28 '19 at 09:43

2 Answers2

1

std::plus is a function object and has to be used in the same manner you would use other function objects.

Minimal example:

#include <iostream>
#include <string>
#include <functional>

int main()
{
    std::string one="one";
    std::string two="two";
    std::string result=std::plus<std::string>()("one","two"); //a temp function object created.
    std::cout << result;

}

See demo here.

P.W
  • 26,289
  • 6
  • 39
  • 76
1

std::plus is a functor, which means you need to create an object of it:

auto adder = std::plus<>{};
auto result = adder(one, two); // result is onetwo

For this reason, you'd never use this as you have: you'd always just simply write one + two.

But it does mean you can use this in the same way you'd use std::greater and the likes: by passing it as a functor which will apply to some container, rather than needing to write your own lambda to add things together.

See What are C++ functors and their uses? for more on functors.

Tas
  • 7,023
  • 3
  • 36
  • 51