Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator as template parameter

Is it possible?

template<operator Op> int Calc(int a, b)
{ return a Op b; }

int main()
{ cout << Calc<+>(5,3); }

If not, is way to achieve this without ifs and switches?

like image 812
Xirdus Avatar asked Sep 17 '10 12:09

Xirdus


People also ask

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

What is a template parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.


2 Answers

You could use functors for this:

template<typename Op> int Calc(int a, int b)
{
    Op o;
    return o(a, b);
}

Calc<std::plus<int>>(5, 3);
like image 101
Nikola Smiljanić Avatar answered Sep 20 '22 15:09

Nikola Smiljanić


No - templates are about types or primitive values.

You can nontheless pass so called function objects that can be called like functions and carry the desired operator functionality (despite having a nice syntax).

The standard library defines several ones, e.g. std::plus for addition ...

#include <functional>

template<typename Op>
int Calc(int a, int b, Op f) { 
  return f(a, b);
}

int main() { 
  cout << Calc(5,3, std::plus());
  cout << Calc(5,3, std::minus());
}
like image 33
Dario Avatar answered Sep 20 '22 15:09

Dario