1

I have currently a working example:

#include <iostream>
#include <future>
int main() {
    auto result = std::async([](int left, int right){return left + right;}, 1, 1);
    std::cout<<"from async I get "<<result.get()<<"\n";

    return 0;
}

This lambda does nothing but a simple addition, but I just fails to replace it with an operator:

auto result = std::async(operator+, 1, 1);

The error says use of undeclared 'operator+'

How do I fix it, to use an operator to replace the lambda?

Koothrappali
  • 157
  • 6

1 Answers1

0

You cannot have a reference or function pointer to a builtin operator see here, but you can use one of the utilities in the <functional> header:

auto result = std::async(std::plus<>{}, 1, 1);

If you're obsessed with passing a reference to an operator, you can have that with a wrapper type:

struct Int { int value; };

Int operator+(const Int& lhs, const Int& rhs)
{
    return Int{lhs.value + rhs.value};
}

auto result = std::async(operator+, Int{1}, Int{1});
std::cout<<"from async I get "<<result.get().value<<"\n";

But this is for understanding what works and what doesn't, I am not proposing that you should do that :)

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Does `std::plus` automatically detect my overloaded functions? – Koothrappali May 28 '21 at 11:46
  • Which overloaded functions? – lubgr May 28 '21 at 11:48
  • Let's say I have my own operator+ overloaded, does `std::plus` takes my function, or does it take the standard one? – Koothrappali May 28 '21 at 11:50
  • @Koothrappali If you look closely at the [documentation](https://en.cppreference.com/w/cpp/utility/functional/plus), you'll see that `std::plus` just basically calls the `+` operator for the given arguments. So yes, if you overloaded that operator, it should be deduced (thanks ADL) – Fareanor May 28 '21 at 11:50
  • Ah, `std::plus<>` does nothing else than invoking `+` on both arguments. Like the lambda in your original example. – lubgr May 28 '21 at 11:51
  • @Koothrappali, std::plus is a template with different implementations. If you give it a type, then it will only add arguments of that type. For example, std::plus will only take (and return) ints. However, std::plus<> with no template arguments, is a special templated version that will take any 2 objects of the same type and return "whatever operator+ returns for those things. So yes, your overloads of any custom types will be used, provided you use `std::plus<>`. – Chris Uzdavinis May 28 '21 at 13:35