0

For example, I want to control the operator between A and B to something depending on the template I'm assigning it to (in main).

// Theoretical operation template function
template <OPERATION>
void Example(int A, int B) {
  A OPERATION B;
}

int main(void) {
  Example< += >(10, 20);
  Example< -= >(10, 20);
  Example< *= >(10, 20);
  Example< |= >(10, 20);
}

I know this is not valid C++ syntax but I'm only doing this for the purpose of explanation. Is this possible? Thanks in advance.

BadUsernameIdea
  • 182
  • 1
  • 12
  • Look in [``](https://en.cppreference.com/w/cpp/header/functional) header, you can find there non-assigning versions of most arithemetic operators. You could write similar templates for assigning operators (note that `Example` takes arguments by value, so you wouldn't notice change after `+=` anyway). – Yksisarvinen May 08 '22 at 18:54
  • 2
    You can use something like [this](https://godbolt.org/z/xKq7nPYo7). Was going to add it as an answer, but the question got closed – Lala5th May 08 '22 at 19:07
  • @Lala5th That solution looks like it can be added as an answer on the target question. Make sure it's not already covered by other answers first. – cigien May 09 '22 at 02:12

1 Answers1

1

You could template Example on the operation, and pass the operation as a third parameter. An easy way to pass the operation is as a lambda or, as @Yksisarvinen commented above, as one of the function objects available in std::functional.

The example below works with arithmetic operators instead of logical operators (you seemed to want to use logical operators in your question's title, but arithmetic operators in your example).

[Demo]

#include <functional>  // plus, minus, multiplies, divides
#include <iostream>  // cout

template <typename Op>
void Example(int a, int b, Op&& op) {
    std::cout << "result = " << op(a, b) << "\n";
}

int main(void) {
    Example(10, 20, std::plus<int>{});
    Example(10, 20, std::minus<int>{});
    Example(10, 20, [](int a, int b) { return a * b; });  // or multiplies
    Example(10, 20, [](int a, int b) { return a / b; });  // or divides
}

// Outputs:
//
//   result = 30
//   result = -10
//   result = 200
//   result = 0
rturrado
  • 7,699
  • 6
  • 42
  • 62