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?
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?
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.
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.